my @array2 =split "\n", @array; print $array2[1];
The problem with your snippet is that split doesn't want a list to split, it wants a scalar. Try this to see for yourself:
use strict; use warnings; my @array = split "\n", argsub(); sub argsub { my $string = "This is\nthe string\nto split.\n"; my @ary = ( "The\ncat", "The\ndog", "The\nmouse" ); if ( wantarray ) { print "List context.\n"; return @ary; } else { print "Scalar context.\n"; return $string; } }
The output is "Scalar context." Since we know that the 2nd argument to the split function must be a scalar, when you stick an array there, the array is evaluated in scalar context. An array evaluated in scalar context returns the number of elements in the array. If you have 100 elements, then you will be trying to split "100" on the newline character, so you end up returning just one element from split to @array2. Attempting to print $array21 fails because there isn't a second element. So you get the error message, "Use of uninitialized value in print at xxxx line yy". (By the way, always tell us what the error message is so we don't have to guess.)
What you should be doing is running split on each element in @array, so that each element is seen by split as one individual scalar. That's a job for a loop. Inside your loop you will put a push function to push the results of 'split' onto your receiving array.
The first loop that comes to mind is probably foreach. To use that method, you would do this:
use strict; use warnings; my @array = ( "This\ndog", "That\nhorse", "Those\nmice" ); my @newarray; foreach my $element ( @array ) { push @newarray, split "\n", $element; } { local $, = "\t"; print @newarray, "\n"; }
But Perl makes it easier on you by providing the cool map looping function. It's not actually called a looping function but it does apply its magic to every element in the list you give it, which implies that there's a loop going on somewhere that you just don't see explicitly. map "maps" to each element whatever you tell it to do within its { block }. It returns a list of the outcome of its work.
Here is how the above snippet would look using map:
use strict; use warnings; my @array = ( "This\ndog", "That\nhorse", "Those\nmice" ); my @newarray = map { split "\n" } @array; { local $, = "\t"; print @newarray, "\n"; }
Have fun with it!
Dave
In reply to Re: split an array into and array???
by davido
in thread split an array into and array???
by splatohara
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |