Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: appending arrays

by Bagarre (Sexton)
on Nov 19, 2003 at 17:11 UTC ( [id://308343]=note: print w/replies, xml ) Need Help??


in reply to appending arrays

This works but isn't pretty.

Any of the GreatOnes want to show us a more elegant solution?

foreach $item (@array1) { push @array3, $item .pop(@array2); }

Entities should not be multiplied unnecessarily.

Replies are listed 'Best First'.
Re: appending arrays
by Abigail-II (Bishop) on Nov 19, 2003 at 17:32 UTC
    That will destroy @array2.

    Abigail

Re: Re: appending arrays
by duff (Parson) on Nov 19, 2003 at 18:14 UTC
    Any of the GreatOnes want to show us a more elegant solution?

    I'm not a GreatOne, but here's how I might have done it assuming that I know the arrays are exactly the same size:

    my $n = $#array1; my @array3 = map { $array1[$_] . $array2[$n-$_] } 0..$n;
Re: Re: appending arrays
by freddo411 (Chaplain) on Nov 19, 2003 at 17:29 UTC
    This works but isn't pretty.

    I beg to differ. Your code is very clean, very easy to understand compared to the "line noise" from Abigal.

    -------------------------------------
    Nothing is too wonderful to be true
    -- Michael Faraday

Re: Re: appending arrays
by QM (Parson) on Nov 19, 2003 at 22:26 UTC
    Eating through the existing arrays:
    push @new, shift(@array1) . pop @array2 while @array1;

    -QM
    --
    Quantum Mechanics: The dreams stuff is made of

Re: Re: appending arrays
by hardburn (Abbot) on Nov 19, 2003 at 17:29 UTC

    That will get the data off the end of @array2, not the beginning. Use shift instead of pop.

    Update: Nothing to see here. Move along. (Must read more carefully next time).

    ----
    I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
    -- Schemer

    : () { :|:& };:

    Note: All code is untested, unless otherwise stated

      That will get the data off the end of @array2, not the beginning.

      Err... Isn't that what the OP wanted? It works fine for me with the OP's data. OK, it destroys @array2, as Abigail-II pointed out. Just for fun, here's a solution that destroys both of the original arrays:

      die "Arrays of different lengths" unless @array1 == @array2; my @array3 = map { shift ( @array1 ) . pop ( @array2 ) } @array1;

      dave

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (4)
As of 2024-04-19 02:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found