Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
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.

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?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1039619]
help
Chatterbox?
[GrandFather]: It's either lines that your browser won't split (no white space) or nodes with <pre> tags which ought to be code tags
[GrandFather]: I haven't noticed the problem for a while, but it can be hard to find the nasty node. If you do find it, consider it and with luck a janitor will fix it

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (3)
As of 2017-05-24 00:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?