[prog] More Perl questions

Jacinta Richardson jarich at perltraining.com.au
Thu Jun 5 23:28:02 EST 2003


On Thu, 5 Jun 2003, Dan Richter wrote:

> I was reading some documentation about a Perl function that returns a list 
> of items in list context, but only returns the first item in scalar context.
> 
> Now, I understand that in Perl, an array can be treated as a scalar (in 
> which case it returns the index of the last element in the array).

A minor correction here.  If you treat a Perl array as a scalar it returns
a value one greater than the index of the last element in the array.  This
value also happens to be the number of elements in the array since the
array indexing starts at zero.  To get the index of the last element of
the array minus one from the array size or look at $#array (if your array
is called "array").

So:

my @array = qw/fish and chips and vinegar/;
	# or @array = ("fish", "and", "chips", "and", "vinegar"); if you
	# don't like qw//;

print $array[0];	# prints "fish";
print @array;		# prints "fishandchipsandvinegar"

my $elements = @array;
print $elements;	# prints 5
print $#array;		# prints 4 (the value of the last index)

> But that's not what this function does: it returns a list in list
> context, but only the first item if it's called in scalar context. 
> 
> How does that work?

There's a Perl function called wantarray (perldoc -f wantarray) that
returns true if the context of the currently executing subroutine is
looking for a list value.  It returns fale if the context is looking for a
scalar.  Hence, I would assume that the function you are referring to
probably looks a little like this inside:

sub some_function
{
	my @list;

	# do stuff with list.

	if(wantarray)
	{
		return @list;
	}
	return $list[0];
}

So:

print some_function();		# calls in list context, gets list out
print some_function() . "\n";	# calls in scalar context, gets first out

my @values = some_function();	# list context, list out
my $value = some_function();	# scalar context, first out.

I hope this helps. If not ask more questions and I'll try to be more
clear.  

All the best,

	Jacinta Richardson

--
   ("`-''-/").___..--''"`-._          |  Jacinta Richardson	    |
    `6_ 6  )   `-.  (     ).`-.__.`)  |  Perl Training Australia    |
    (_Y_.)'  ._   )  `._ `. ``-..-'   |      +613 9354 6001 	    |  
  _..`--'_..-_/  /--'_.' ,'           | contact at perltraining.com.au |
(il),-''  (li),'  ((!.-'              |   www.perltraining.com.au   |



More information about the Programming mailing list