Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: filtering and dividing an array

by Dhanasekar (Acolyte)
on Nov 29, 2008 at 10:31 UTC ( #726760=note: print w/ replies, xml ) Need Help??


in reply to filtering and dividing an array

For joining the two arrays into a single array below is the example. The operation will be done for the number of elements in the array1, i.e., if there are 4 elements in the list then first 4 elements will be processed irrespective of the number of elements in array2.

#/usr/bin/perl use Data::Dumper; ## Populating the Arrays with some values. @array1 = ( 1,2,3,4 ) ; @array2 = ( 'one', 'two', 'three', 'four' ); ## Initialise the index for the array $i = 0; ## Join the two array 'array1', 'array2' in a single array named 'arra +y' map { $array[$i][0] = $array1[$i] ; $array[$i][1] = $array2[$i]; $i++ + } @array1 ; print Dumper @array;
I am not sure whether you have asked this !!


Comment on Re: filtering and dividing an array
Download Code
Re^2: filtering and dividing an array
by oko1 (Deacon) on Nov 29, 2008 at 14:03 UTC

    That's not exactly what I would call "joining two arrays"; you've actually created a List of Lists. Joining arrays is much simpler than that:

    my @a = 1 .. 4; my @b = "a" .. "d"; my @c = (@a, @b); # You could even do this - no need to create a new variable: @a = (@a, @b); # Or... push @a, @b;

    There's also no need for the complex and hard-to-read map statement if you wanted to create a LoL; just as in your example, this assumes that the first array is the same length or shorter than the second one:

    my @c; push @c, [ $a[$_], $b[$_] ] for 0 .. $#a;

    Update: Added the "Or..." "push" method.


    --
    "Language shapes the way we think, and determines what we can think about."
    -- B. L. Whorf

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (5)
As of 2014-09-19 02:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (129 votes), past polls