Click to See Complete Forum and Search --> : Arrays and arrays of arrays
yitzle
01-28-2007, 04:35 PM
If I got an array of strings and I want to split those strings and stick the resulting array back into the original array, how do I do it.
Or, better yet, what's wrong with my code?
@temp;
for ($i = 0; $i < $size1; $i++) {
@temp = split / \t/, $setOne[$i] . "\n";
@setOne[$i] = @temp;
}
marybeshaw
01-28-2007, 09:56 PM
@temp;
for ($i = 0; $i < $size1; $i++) {
@temp = split / t/, $setOne[$i] . "\n";
@setOne[$i] = @temp;
}
my $temp;
foreach my $
marybeshaw
01-28-2007, 10:05 PM
You can do it in one statement using "map". If you're trying to split on a tab, use "\t". Also, your '. "\n"' is implicitly forcing a scalar on the split, causing it to return the number of fields in your array and then a \n. Add the "\n" later - when you output your data.
@setOne = map { split("\t", $_) } @setOne;
Good luck.
Mary
marybeshaw
01-28-2007, 10:10 PM
Your ."\n" is throwing you off. Remove it, and it should work fine. You can do better, though:
@setOne = map { split(/\t/, $_) } @setOne;
yitzle
01-29-2007, 10:28 AM
Guess I should look up "map"s...
yitzle
01-29-2007, 10:33 AM
@temp;
for ($i = 0; $i < $size1; $i++) {
@temp = split " \t", $setOne[$i];
@setOne[$i] = @temp;
}
print @temp;
print @setOne[2];
Dunno. Prints temp file. setOne only has one element printed, as if it were an array of strings and not arrays.
yitzle
01-29-2007, 11:17 AM
OK. I used the map line.
When I do `print @setOne;` it prints all the data in a squre. Lines across and newline where expected.
But to access the data, it seems like I need to access it like a linear (1D) array.
I'm going to try to take slices of the array and use that to construct a 2D array.
marybeshaw
01-29-2007, 02:07 PM
Map just turns an array into a different array based on the return value of the subroutine between brackets. I'm sure you've already figured that one out, though.
In perl, it's best to not print arrays directly.
To print data from an array, use join statements. It turns an array into a string with the delimiter as the first argument. Since you have nested arrays, you'll need to map it back out. Something like this should work. The @{} just explicitly tells the Perl interpreter to use an array.
print join("\n", map { join(", ", @{$_}) } @setOne);
to access the data, try something like this:
foreach my $one (@setOne) {
my @line = @{$one};
# you're in - @line is one line, array style
foreach my $item (@line) {
# you're in one field of one line
}
}
I usually use references to hashes instead of arrays. Then I can access the data based on a key string instead of a number. It eliminates search loops. Have you used hashes before?