Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

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]
[davies]: LanX: No. The mayor of London would better be described as the transport commisar for London. S/h/it doesn't have a tenth of the power of La Sturgeon (and therefore does <10% of the damage).
[LanX]: xD ... complicated countrie(s)
LanX reigned by the Duke of Normandy
[davies]: LanX: Politicians making jobs for each other, really. Results in unnecessary complications and tax bills with up to 5 levels of Govt busily inventing new crimes for people to commit.

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (9)
As of 2017-12-15 18:22 GMT
Find Nodes?
    Voting Booth?
    What programming language do you hate the most?

    Results (441 votes). Check out past polls.