Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: Get even postion elements in an array

by LanX (Saint)
on Nov 16, 2010 at 12:27 UTC ( [id://871703]=note: print w/replies, xml ) Need Help??


in reply to Get even postion elements in an array

$a=1;print grep {$a=1-$a} @input

or, more cryptic

$a=1;print grep {$a^=1} @input

Cheers Rolf

Replies are listed 'Best First'.
Re^2: Get even postion elements in an array
by happy.barney (Friar) on Nov 16, 2010 at 12:58 UTC
    @output = @input[ grep $_ & 1, 0 .. $#input];
    ($mod, $val) = (2, 1); @output = @input[ grep $_ % $mod == $val, 0 .. $#input];
Re^2: Get even postion elements in an array
by anonymized user 468275 (Curate) on Nov 16, 2010 at 15:36 UTC
    Why not be LESS cryptic, e.g.:-
    my $flipflop = 1; my @result = grep { $flipflop = not $flipflop; }, @input;

    One world, one people

      I prefer reusable idioms.

      Here not is indeed more readable, but it won't produce 0 for false, which could be counterintuitive in other cases.

      $flipflop needs to be declared, while $a (and $b) is already global as part of the sort idiom, which is a similar case of using a code block.

      $a=1; my @result = grep { $a = not $a }, @input;

      At the end it's a matter of taste. ^= is shorter, = not is clearer, but =1- can equally be used in most other languages, making it an universally understood idiom.

      Cheers Rolf

        Reusable idioms are an open block to your thinking. They are not the same as reusable code. '' is just as false as 0 and is often preferable -- for example, a routine returns or sets a scalar by reference originating from a unix exit code, 0 being unix success, so '' is the best value for "i had to abort earlier than that" $a is not a global, it's a special variable for use in sort blocks, that shouldn't be abused especially by habit -- one day a sort routine will come back to bite you in the bottom. Are you trying to say that not declaring locally and instead using global variables is a virtue? Many here will disagree.

        One world, one people

Re^2: Get even postion elements in an array
by LanX (Saint) on Nov 16, 2010 at 16:05 UTC
    for completeness, an application of the new state feature for implicit initialization and scoping:

    DB<23> use feature "state"; print grep { state $ff ^= 1 } 0..9 02468 DB<24> use feature "state"; print grep { not state $ff ^= 1 } 0..9 13579

    Cheers Rolf

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (4)
As of 2024-04-24 02:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found