3

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?

simbabque
  • 53,749
  • 8
  • 73
  • 136
aman
  • 365
  • 3
  • 13

3 Answers3

9

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • 1
    Might be worth mentioning how an assignment of `my ( $fruit ) = ( 'apple', 'pear', 'banana' );` would handle compared to `my $fruit =`. – Sobrique Oct 29 '15 at 12:20
2

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.

Diego Sevilla
  • 28,636
  • 4
  • 59
  • 87
1

Those parens indirectly affect the context in which the right-hand side of the assignment is evaluated.

my ($x) = LIST;
(my $x) = LIST;
my $x = SCALAR;

I cover this in detail in Mini-Tutorial: Scalar vs List Assignment Operator.

In this case,

# grep in list context returns all the matches,
# the first of which is assigned to $fruit.
my ($fruit) = grep { $_ eq 'apple' } @objects;

# grep in scalar context returns the number of matches,
# which is assigned to `$num_fruits`.
my $num_fruits = grep { $_ eq 'apple' } @objects;
ikegami
  • 367,544
  • 15
  • 269
  • 518