Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re^3: map BLOCK evaluation context

by vsespb (Hermit)
on Mar 08, 2013 at 14:51 UTC ( #1022437=note: print w/ replies, xml ) Need Help??


in reply to Re^2: map BLOCK evaluation context
in thread map BLOCK evaluation context

Aha, you're right. The thing was that

print "C:"; for (qq{ab cd}) { print /(\S+)/g or die; # prints "C:abcd", list context again } print "\n";
was evaluated just like
print "C:"; for (qq{ab cd}) { print(/(\S+)/g) or die; } print "\n";
It can be fixed like this:
print "D:"; for (qq{ab cd}) { print /(\S+)/g || die; } print "\n";
However seems "or" not always enforces scalar context:
my @a = (1,2,3); print "X:"; print (0 || @a); print "\n"; print "Y:"; print (@a || 0); print "\n";
prints
X:123 Y:3


Comment on Re^3: map BLOCK evaluation context
Select or Download Code
Re^4: map BLOCK evaluation context
by Athanasius (Monsignor) on Mar 08, 2013 at 15:43 UTC

    After noting that:

    The && and || operators differ from C’s in that, rather than returning 0 or 1, they return the last value evaluated.

    the Camel Book (4th Edition, 2012, page 120) goes on to explain that the || operator imposes scalar context on its left operand to facilitate chaining in assignment:

    ...this has the delightful result that you can select the first of a series of scalar values that happens to be true. Thus, a reasonably portable way to find out the user’s home directory might be:
    my $home = $ENV{HOME} || $ENV{LOGDIR} || (getpwuid($<)[7] || die "You're homeless!\n";
    On the other hand, since the left argument is always evaluated in scalar context, you can’t use || for selecting between two aggregates for assignment:
    @a = @b || @c; # This doesn't do the right thing @a = scalar(@b) || @c; # because it really means this. @a = @b ? @b : @c; # This works fine though.

    (There is a truncated version of this explanation in Logical Defined Or in perlop, but the Camel Book is clearer.)

    As tobyink noted above, scalar context is not imposed on the right operand.

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

      Thanks!

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1022437]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (7)
As of 2014-12-25 11:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (160 votes), past polls