Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Fetch every other item in a list

by BooK (Curate)
on Oct 24, 2000 at 03:02 UTC ( [id://38046]=obfuscated: print w/replies, xml ) Need Help??

This is not obfuscation, but it might be useful and didn't quite fit anywhere else...
If you want to get every other item in a list or array, and don't care if the order is preserved, you can use this:

@a = keys %{{@a}} # for even indices @a = values %{{@a}} # for odd indices

This is quite quick and powerful, but alas doesn't preserve the order.

Replies are listed 'Best First'.
RE: Fetch every other item in a list
by japhy (Canon) on Oct 24, 2000 at 03:22 UTC
    Also breaks on lists like ('foo', 'bar', 'foo', 'blat'). I'd suggest:
    @even = @array[map 2*$_, 0..$#array/2]; @odd = @array[map 2*$_+1, 0..$#array/2];
    You can obfuscate this if you wish...

    $_="goto+F.print+chop;\n=yhpaj";F1:eval
      Blew my last vote of the day on that post, japhy. =) I was coming back to post the basically same thing in an update to my post.

      --
      $you = new YOU;
      honk() if $you->love(perl)

RE (tilly) 1: Fetch every other item in a list
by tilly (Archbishop) on Oct 24, 2000 at 05:20 UTC
    Try the following for a strange version that you might find handy in obfuscation:
    #! /usr/bin/perl (push @odd, $_)...(push @even, $_) foreach @ARGV; print map "$_\n", "Odd arguments:", (map " $_", @odd), "\nEven arguments:", (map " $_", @even);
    Be warned that you cannot construct a useful function this way though because it remembers state from function call to function call!
RE: Fetch every other item in a list
by extremely (Priest) on Oct 24, 2000 at 03:33 UTC
    Hmmm.. turn on "use strict;" and "-w" and try it with this array:
    #!/usr/bin/perl -w use strict; my @list=("one", 1, "two", 2, 3, "Three", 3, "four", 5); print join("][", keys %{{@list}})."\n"; print join("][", values %{{@list}})."\n";

    This code is evil on odd sized lists, any list that may have duplicate "keys", and on the eyes. =) Good for "obfus" work where you know what your data is tho...

    --
    $you = new YOU;
    honk() if $you->love(perl)

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (4)
As of 2025-06-16 04:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.