Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

perlish mapping a list to triples

by water (Deacon)
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

Replies are listed 'Best First'.
Re: perlish mapping a list to triples
by dave_the_m (Monsignor) on Jun 06, 2004 at 01:38 UTC
    something like:
    push @b, [splice @a, 0, 3 ] while @a;


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?

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

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (4)
As of 2020-06-01 05:36 GMT
Find Nodes?
    Voting Booth?

    No recent polls found