scalar function

F

fatted

Consider 2 statements:

my $value = 3 + @array;
my $value = 3 + scalar(@array);

They both result in $value having the same value (as far as I've seen).

Is there any difference, or to put it another way, what's the point in using scalar?
 
G

Gunnar Hjalmarsson

fatted said:
Consider 2 statements:

my $value = 3 + @array;
my $value = 3 + scalar(@array);

They both result in $value having the same value (as far as I've
seen).

Is there any difference, or to put it another way, what's the point
in using scalar?

The point with using scalar is to _ensure_ a return value in scalar
context. In this case, you get it implicitly - out from context :) -
by including @array in an addition.
 
D

David Bouman

fatted said:
Consider 2 statements:

my $value = 3 + @array;
my $value = 3 + scalar(@array);

They both result in $value having the same value (as far as I've seen).

Your insights are correct;
Is there any difference, or to put it another way, what's the point in using scalar?

Consider:

print 3, @array;
print 3, scalar(@array);
 
S

Shawn Corey

Hi,

The point of the scalar function is to tell Perl you want the number of
elements of the array rather than the array itself in those contexts
where it's unclear whether the context is scalar or array.

Example: parameters of a function.

&foo( @arr ); # send the array
&foo( scalar( @arr )); # send the number of elements

If you're not sure, use it anyway. I always use it just to make
understanding the program clearer.
 
D

David Bouman

Shawn said:
The point of the scalar function is to tell Perl you want the number
of elements of the array rather than the array itself in those
contexts where it's unclear whether the context is scalar or array.

The point of scalar EXPR is to force a scalar context upon it's
expression argument. It just so happens that an array in scalar
context evaluates to its number of elements but that's not the
intended purpose of the scalar operator.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,109
Messages
2,570,671
Members
47,262
Latest member
EffiePju4

Latest Threads

Top