sanmonkey has asked for the wisdom of the Perl Monks concerning the following question:

Will someone be kind enough to explain the technicalities behind the following scalar assignment ? my $scalar = grep /\d+/ `some command`; sets $scalar to 0 or 1 depending on whether grep was successful in matching the regexp or not. my ($scalar) = grep /\d+/ `some command`; Sets $scalar to the output of grep. Why so ? Thanks much in advance

Replies are listed 'Best First'.
Re: Scalar assignment question
by toolic (Bishop) on Jun 17, 2010 at 14:34 UTC
    my $scalar forces the return value of grep to a scalar context, in which case, it returns the number of matches.

    my ($scalar) forces the return value of grep to a list context, in which case it returns the first match.

    Consider:

    use strict; use warnings; # MATCHES { my $scalar = grep /\d+/, 1 .. 5; print "$scalar\n"; } { my ($scalar) = grep /\d+/, 1 .. 5; print "$scalar\n"; } # NO MATCHES { my $scalar = grep /\d+/, 'a' .. 'z'; print "$scalar\n"; } { my ($scalar) = grep /\d+/, 'a' .. 'z'; print( (defined $scalar) ? "$scalar\n" : "undefined\n" ); } __END__ 5 1 0 undefined

    See also: List value constructors

    Update: added 'no matches' to example

Re: Scalar assignment question
by Utilitarian (Vicar) on Jun 17, 2010 at 14:32 UTC
    perldoc -f grep
    ... 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.
    In the first instance it sets scalar to the the number of matches.
    In the second instance it actually only sets the value of $scalar to the first returned value as surrounding a scalar value in () puts the scalar into a list context.

    print "Good ",qw(night morning afternoon evening)[(localtime)[2]/6]," fellow monks."
Re: Scalar assignment question
by cdarke (Prior) on Jun 17, 2010 at 16:14 UTC
    The parentheses indicate list context. For example:
    my @fred = qw(42 43 44 45); my ($q, $x, $y, $z) = grep /\d+/, @fred; print "$q $x $y $z\n";
    I don't think you would be surprised at the result:
    42 43 44 45
    So $q is 42. Now remove $z:
    ($q, $x, $y) = grep /\d+/, @fred; print "$q $x $y\n";
    Now we get just 42 43 44That is $q has not changed. Now remove $y:
    ($q, $x) = grep /\d+/, @fred; print "$x\n";
    and we get
    42 43
    $q still is unchanged. Finally remove $x:
    ($q) = grep /\d+/, @fred; print "$q\n";
    and $q is still:
    42
Re: Scalar assignment question
by choroba (Cardinal) on Jun 17, 2010 at 14:34 UTC