Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: Making little array babies

by jdporter (Paladin)
on Apr 12, 2004 at 17:43 UTC ( [id://344455]=note: print w/replies, xml ) Need Help??


in reply to Making little array babies

I have a solution which I believe is better because it does not change the source array (@images), as do the other ideas suggested so far.
my @a = qw( a b c d e f g ); my $n = 3; my @b; for ( my $i = 0; $i <= $#a; $i += $n ) { push @b, [ @a[ $i .. $i+$n-1 ] ]; }
It's also really simple. :-)

jdporter
The 6th Rule of Perl Club is -- There is no Rule #6.

Replies are listed 'Best First'.
Re: Re: Making little array babies
by revdiablo (Prior) on Apr 12, 2004 at 21:50 UTC

    To aid in my irrational goal to never use the C-style for loop in Perl -- as well as the more widely accepted goal of TMTOWTDI -- here's how I'd do that:

    my @a = qw(a b c d e f g); my $n = 3; my @b; for (0 .. $#a/$n) { push @b, [ @a[$_*$n .. $_*$n+$n-1] ]; }

    I was going to make the case that I like to avoid the C-style for loop because it looks ugly in Perl with all the sigils clogging things up, but after I typed out my alternative, I realized its readability is not much better. *shrug*

      Well, the direct equivalent* of mine, above, would be:
      (* other than scoping issues of $i)

      my $i = 0; while ( $i <= $#a ) { push @b, [ @a[ $i .. $i+$n-1 ] ]; } continue { $i += $n; }
      Thing I don't like about yours is the incessant multiplication by $n.

      jdporter
      The 6th Rule of Perl Club is -- There is no Rule #6.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (3)
As of 2024-04-26 01:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found