Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Non-destructive array processing

by BrowserUk (Patriarch)
on Jan 20, 2003 at 22:54 UTC ( [id://228517]=note: print w/replies, xml ) Need Help??


in reply to Non-destructive array processing

Another alternative, which I think I prefer. Best thing is you don't get "Use of uninitialized value in join or string at ..." if the array size isn't an exact multiple of the chunk size.

sub getIter (\@$;$) { my ($ref, $size, $next) = @_; $next ||= 0; return sub { $next = 0, return () unless $next <= $#$ref; my $start = $next; $next = $next+$size <= $#$ref ? $next+$size-1 : $#$ref; @$ref[ $start .. $next++ ] } } my $iter = getIter( @array, 2 ); while( my @chunk = $iter->() ) { print "Chunk: @chunk"; }

Examine what is said, not who speaks.

The 7th Rule of perl club is -- pearl clubs are easily damaged. Use a diamond club instead.

Replies are listed 'Best First'.
Re: Re: Non-destructive array processing
by dragonchild (Archbishop) on Jan 21, 2003 at 16:21 UTC
    In what context would you use the $next variable? It looks to be useful only for setting a first value to return. (Sorta like "Skip the first N values" thingy...)

    Is that what it is?

    ------
    We are the carpenters and bricklayers of the Information Age.

    Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

      That's it exactly. Skip the $first n and then give'm to me in chunks of $size after that.


      Examine what is said, not who speaks.

      The 7th Rule of perl club is -- pearl clubs are easily damaged. Use a diamond club instead.

Re: Re: Non-destructive array processing
by Juerd (Abbot) on Jan 21, 2003 at 19:30 UTC

    Best thing is you don't get "Use of uninitialized value in join or string at ..." if the array size isn't an exact multiple of the chunk size.

    I *want* those warnings. If the array length is not an exact multiple of the chunk size, something is wrong, and I would like to be informed. In production code, I'd let it croak if @array % 2 even before looping.

    Juerd
    - http://juerd.nl/
    - spamcollector_perlmonks@juerd.nl (do not use).
    

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (7)
As of 2024-04-19 08:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found