Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: Mini-Tutorial: Working with Odd/Even Elements

by moritz (Cardinal)
on Jul 09, 2009 at 18:45 UTC ( #778656=note: print w/replies, xml ) Need Help??


in reply to Mini-Tutorial: Working with Odd/Even Elements

my $t = 1; grep { $t^=1 } LIST

If you're on perl-5.10 or newer, you can also use a state variable inside the block, and thus not "tainting" the outer scope:

use 5.010; say grep { state $t = 1; $t ^= 1} <a b c d>; # prints: bd

Replies are listed 'Best First'.
Re^2: Mini-Tutorial: Working with Odd/Even Elements
by ikegami (Patriarch) on Jul 09, 2009 at 19:22 UTC
    That's not very useful outside of one-liners since it'll remember the state from the previous loop pass or function call.
Re^2: Mini-Tutorial: Working with Odd/Even Elements
by JavaFan (Canon) on Jul 09, 2009 at 19:02 UTC
    $ perl -wE 'say grep {state $t ^= 1} qw[a b c d]' ac $
      oops...
      $ perl -de 1 ... DB<1> use 5.010; sub a { grep { state $t ^= 1 } @_ } DB<2> x a(1..5) 0 1 1 3 2 5 DB<3> x a(1..5) 0 2 1 4
        That's a feature! You first get the odd elements, then the evens! ;-) ;-)

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (4)
As of 2023-09-23 14:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?