Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: split every other value

by beable (Friar)
on Aug 07, 2004 at 00:15 UTC ( [id://380780]=note: print w/replies, xml ) Need Help??


in reply to split every other value

#!/usr/bin/perl use strict; use warnings; my $scalar = '1,2,3,4,5,6,7,8'; my @array = split(/\,/,$scalar); print "array = @array\n"; # do the odd/even split my @odd = (); my @even = (); while (@array) { my $odd = shift @array; my $even = shift @array; if (defined $odd) { push @odd, $odd; } if (defined $even) { push @even, $even; } } print "odd = @odd, even = @even\n"; __END__

Replies are listed 'Best First'.
Re^2: split every other value
by Aristotle (Chancellor) on Aug 07, 2004 at 00:32 UTC

    You got your odd/even mixed up. The first element is at index 0, which is even. Also, enter splice and statement modifiers.

    while( @array ) { my ( $even, $odd ) = splice @array, 0, 2; push @odd, $odd if defined $odd; push @even, $even if defined $even; }

    It is worth noting that this would be buggy if the list could possibly have undefs in it (not the case here; but I'd put a comment to that effect in the code).

    Obscure trickery for the fun of reducing it further, but don't do this at home:

    ( $even[ @even ], $odd[ @odd ] ) = splice @array, 0, 2 while @array;

    Makeshifts last the longest.

      I shouldn't have used the names "@odd" and "@even", seeing as how we're supposed to be dealing with text. So here's a program which doesn't use those terribly misleading names, and deals with undefs.

      #!/usr/bin/perl use strict; use warnings; my @array = map{chr} ('32' .. '126'); push @array, undef, undef; unshift @array, undef, undef, undef; # split elements into two arrays my (@arr0, @arr1); while (@array > 1) { my ($el0, $el1) = splice @array, 0, 2; push @arr0, $el0; push @arr1, $el1; } # get the last element if there is one if(@array) { push @arr0, shift @array; } # check that all elements were gotten die "still elements left" if (@array); print "arr0 = @arr0\narr1 = @arr1\n"; __END__

        If you do away with the conditionals like that, the temporaries in the while loop are superfluous.

        my ( @arr0, @arr1 ); while( @array > 1 ) { push @arr0, shift @array; push @arr1, shift @array; } push @arr0, shift @array if @array;

        Or you could pull the conditional back into the loop:

        my ( @arr0, @arr1 ); while( @array ) { push @arr0, shift @array; push @arr1, shift @array if @array; }

        Makeshifts last the longest.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (4)
As of 2024-04-18 07:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found