I know that similar topics have been addressed here, but I have run into a problem that seems to me to be due to my misunderstanding about how massive slices are interpolated in the context of a foreach loop. I can’t understand where I was wrong, so I’m looking for some ideas.
I have a 2D array with a variable number of rows. For example, goals:
@2DArray = (['str1', 1, 2, 'E', val1, val2, val3]
['str2', 3, 4, 'E', val4, val5, val6]
['str4', 5, 6, 'F', val7, val8, val9])
I want to create a new array with additional columns that includes some of the rows in the original array only if they contain the string "E" in column 3. Also, for the rows that I want to include in my new array, I only want a subset of the columns. and I want this subset in a different order. The ultimate goal is to generate the output of the correct format needed for downstream scenarios.
Here is my attempt to do this:
my $projName = 'test';
my $i = 1;
my @Newarray
my @Newarray_element;
foreach (@2DArray) {
if (${$_}[3] eq 'E') {
${$_}[3] = $i;
${$_}[5] = '+';
@Newarray_element = ("$projName$i", @$_[0,1,2,5,3], 'STR', 11, 11);
$i++;
push (@Newarray, \@Newarray_element);
}
next;
}
print (join("\t", @$_), "\n") for @Newarray;
However, if I do this, I get:
test2 str2 3 4 + 2 STR 11 11
test2 str2 3 4 + 2 STR 11 11
That is, my new array will have a row for each row of the original array with "E" in column 3, but each row is populated with the values from the last row processed by the loop.
, , 2D- foreach, , , 2D-, "E" 3, , , . , :
my @Newarray;
my $i = 1;
foreach (@2Darray) {
if (${$_}[3] eq "E") {
${$_}[3] = $i;
${$_}[5] = '+';
$i++;
push (@Newarray, \@$_);
}
next;
}
print (join("\t", @$_), "\n") for @Newarray;
, :
* &
str1 1 2 1 val1 + val3
str2 3 4 2 val4 + val6
, *, 3 5. : ?