in reply to Decompose a String into Tuples (Faster and Compact Way)

use strict; use warnings; use Data::Dumper; while (<DATA>) { chomp; print Dumper decomp($_); } sub decomp { my @ret; @_ = split / /, $_[0]; for (my $i = 0; $i < $#_; $i += 2) { push @ret, [$_[$i], $_[$i+1], $_[$i+2]]; } return \@ret; } __DATA__ X -4 Y 3 Z W 1 X -4 Y 3 Z X 2 Y A -4 B -4 C -4 A -4 B

Replies are listed 'Best First'.
Re^2: Decompose a String into Tuples (Faster and Compact Way)
by Tortue (Scribe) on Oct 12, 2005 at 19:57 UTC
    (Um, for the above to do what the op wants, I think you need something like  push @ret, "@_[$i..$i+2]"; instead of  push @ret, [$_[$i], $_[$i+1], $_[$i+2]];)

    Here's my shifty suggestion:

    sub decomp { @_ = split / /, shift; return [ map { join " ", (shift, shift, $_[0]) } (1..@_/2) ]; }
    update: shorter and generalizable to producing any size tuple:
    sub decomp { my $n = 2; # for n+1-uples @_ = split / /, shift; return [ map { $_*=$n; "@_[$_..$_+$n]" } 0..@_/$n-1 ]; }