I have a file which contains multiple rows and columns of data. I need to read in the file and print when a particular column matches a particular number.
This is what I have below, I currently do not get any results:
my $old_flag = 'file1.txt';
my $new_flag = 'file2.txt';
open (IN, "<$old_flag");
open (OUT, "+>$new_flag");
my @data = <IN>;
for (@data) {
my @old_flag;
chomp;
@old_flag = split /\t/, $_;
push (@records, @old_flag);
}
foreach my $record (@records) {
if($record[2] == 11125) {
print OUT "$record[2]\n";
} else {
next;
}
}
You probably think you are creating a two-dimensional array by doing this
push (@records, @old_flag);
But in fact you are just pushing values onto a regular array. And here, you think you are accessing a two-dimensional array
foreach my $record(@records){
if($record[2] == 11125) {
But in fact, you are just checking the same non-existent array element every loop iteration. You see $record
and $record[2]
refer to two different variables. The latter is just the third element of the @record
array. Which you have never declared. If you had used use strict
you would have gotten the error:
Global symbol "@record" requires explicit package name at foo.pl line 12
What you might do to fix it is:
push @records, \@old_flag; # works because @old_flag is a lexical variable
...
foreach my $record (@records) {
if($record->[2] == 11125) {
Here, you are treating $record
as an array reference, which it is.
You are having these problems because you are not using
use strict;
use warnings;
These two pragmas have a certain learning curve, but they will prevent you from making simple mistakes and typos and will reduce your debugging time.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.