Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

perlish mapping a list to triples

by water (Chaplain)
on Jun 06, 2004 at 01:34 UTC ( #361716=perlquestion: print w/ replies, xml ) Need Help??
water has asked for the wisdom of the Perl Monks concerning the following question:

Hi --

I have list, @x, that is actually a flattened list triples:

@x = (( $x1a, $x1b, $x1c), ( $x2a, $x2b, $x2c), ( $x3a, $x3b, $x3c), . +.. etc ... ($xna, $xnb, $xnc));
What's the nice perlish to map this back to an LOL of triples:
[[$x1a, $x1b, $x1c], [$x2a, $x2b, $x2c], [$x3a, $x3b, $x3c], ... etc . +.. [$xna, $xnb, $xnc]]
I'm using an explicit loop with three  shifts to pull off the elements by threes. It works, but I'd like to learn the more idiomatic perlish solution. Thanks for the insight --

bottled water

Comment on perlish mapping a list to triples
Select or Download Code
Re: perlish mapping a list to triples
by dave_the_m (Parson) on Jun 06, 2004 at 01:38 UTC
    something like:
    push @b, [splice @a, 0, 3 ] while @a;
    perhaps?

    Dave.

Re: perlish mapping a list to triples
by BrowserUk (Pope) on Jun 06, 2004 at 02:12 UTC

    If you don't want to destroy the original array with splice then you could do

    my @a = 1..30; my @b = map{ [ @a[ $_ .. $_ +2 ] ] } map{ $_ *3 } 0 .. $#a/3; print "@$_" for @b;; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30

    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "Think for yourself!" - Abigail
Re: perlish mapping a list to triples
by Django (Pilgrim) on Jun 06, 2004 at 11:56 UTC

    Here's a variant of BrowserUks approach:

    my @a = (1..30); my @b; my $p = 0; push @b,[ @a[map{$p++}(1..3)] ] while $p < $#a; print map{"@$_\n"}@b;

    -- Django
    "Why don't we ever challenge the spherical earth theory?"

Re: perlish mapping a list to triples
by ambrus (Abbot) on Jun 06, 2004 at 18:28 UTC

    You asked for a perlish way, so here is it. (Or at least this is my idea of perlish.) (A lispish way would be a tail-recursive function.)

    use Data::Dumper; @arr= 1..18; (@{$aoa[@aoa]}[0..2], @arr) = @arr while @arr; $aoa= [@aoa]; print Dumper $aoa;

    Update: hihi, I've just seen the sign under the post:

    bottled water

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://361716]
Approved by Paladin
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (5)
As of 2014-08-01 02:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (256 votes), past polls