Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

pushing onto multiple arrays

by martymart (Deacon)
on Mar 31, 2004 at 11:09 UTC ( [id://341273]=perlquestion: print w/replies, xml ) Need Help??

martymart has asked for the wisdom of the Perl Monks concerning the following question:

Fellow Monks,
is it possible to push stuff onto two (or more) arrays at the same time?
For example:
push @array, "some text"; push @array2, "some text";
is there an easier way to do this, something like
push (@array,@array2), "some text";
although obviously this doesn't work, or I wouldn't be asking here. Apologies in advance if this is a really obvious answer, it just doesn't seem to be covered in my programming perl book (second edition)

Many Thanks,
Martymart

Replies are listed 'Best First'.
Re: pushing onto multiple arrays
by broquaint (Abbot) on Mar 31, 2004 at 11:12 UTC
    A simple for should do it e.g
    my(@a1, @a2); push @$_, 'a string' for \@a1, \@a2; print "a1: @a1\na2: @a2\n"; __output__ a1: a string a2: a string
    HTH

    _________
    broquaint

Re: pushing onto multiple arrays
by Hena (Friar) on Mar 31, 2004 at 11:15 UTC
    Using arrays of arrays it gets easier. Something like this:
    my @list; foreach (0 .. 5) { push (@{$list[$_]},"some text"); }
    UPDATE: fix typo in code, thanks Happy-the-monk :)
Re: pushing onto multiple arrays
by Hofmator (Curate) on Mar 31, 2004 at 13:05 UTC
    Going with broquaint's solution, if you should need it more than once, put it into a sub, e.g.
    sub mpush { my $arrays = shift; local $_; push @$_, @_ for @$arrays; } mpush [\@array, \@array2], "some text";

    -- Hofmator

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (4)
As of 2024-04-26 06:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found