Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between $name and ($name) variable in perl [duplicate]

Tags:

perl

I was wondering whether anyone can explain the difference between the $name and ($name).

For example:

my @objects = ('specs','books','apple');
my ($fruit) = grep { $_ eq 'apple'} @objects;

This gives the result for $fruit = 'apple'. However, if the second statement is modified as:

$fruit = grep { $_ eq 'apple'} @objects;

The value for the fruit is evaluated to 1. Is this related/specific to grep?

like image 611
aman Avatar asked Nov 29 '25 05:11

aman


2 Answers

my $fruit = assigns into scalar context.

my ($fruit) = assigns into list context (as would my @fruit =).

The grep documentation says:

returns the list value consisting of those elements for which the expression evaluated to true. In scalar context, returns the number of times the expression was true.

It is effectively using wantarray internally to determine what type of return value it should give. You can use that in your own subroutines to get a similar effect, but you might not want to.

like image 92
Quentin Avatar answered Dec 01 '25 19:12

Quentin


This has to do with different receiving cotexts in Perl. If you use a scalar variable, a function returning a list (as it is grep) will return the length of the list.

With the second form (my ($fruit)) you force a list context with one element, and this is why $fruit has the value of the only result of the list. Note that you're forcing only a one-element list, so $fruit will get just the first element. The rest elements of the list (if any) will be silently lost.

like image 24
Diego Sevilla Avatar answered Dec 01 '25 20:12

Diego Sevilla



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!