Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

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.

Replies are listed 'Best First'.
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
Re^3: substituting values in an array
by Lotus1 (Curate) on Jun 18, 2013 at 20:25 UTC

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1039619]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (7)
As of 2018-06-24 22:49 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (126 votes). Check out past polls.