Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re^2: substituting values in an array

by sundialsvc4 (Abbot)
on Jun 18, 2013 at 18:02 UTC ( #1039619=note: print w/ replies, xml ) Need Help??


in reply to Re: substituting values in an array
in thread substituting values in an array

Take notice of what Toby suggests here.   Notice that there is no indexing going on, and that a change to a scalar variable (the built-in $_ in this case) effects a change in the value of the array element.   The reason is that it is a reference to that element.   The variable walks down the entire length of the array, and, because it is a reference to each value in turn, and not merely a copy of it, it can change it.

The somewhat “golf”-ish use of && is a “short-circuit” boolean-AND.   If the expression on the left-hand side is True, the expression on the right-hand side is evaluated (and does something); otherwise it is not evaluated at all (since False AND anything is known to always be False).

This kind of “brevity of expression” is very common in Perl.


Comment on Re^2: substituting values in an array
Re^3: substituting values in an array
by Lotus1 (Chaplain) on Jun 18, 2013 at 20:25 UTC
Re^3: substituting values in an array
by tobyink (Abbot) on Jun 18, 2013 at 23:01 UTC

    In this case, the golf is not just for leisure. You'd have to dig out the XS to write a faster solution. On a large array, it's about twice as fast as using map, and about 50% faster than using (admittedly somewhat more readable) for and if blocks.

    Also quite fast (though just a teeny bit slower) would be:

    $_ = ($_ > 200) ? 200 : $_ for @array;

    ... though that might degrade quite badly on a tied array as it performs unnecessary extra FETCH and STORE operations.

    package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (9)
As of 2014-12-27 20:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

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





    Results (177 votes), past polls