简体   繁体   English

引用数组perl中的列

[英]Referencing a column in an array perl

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. 您会看到$record$record[2]引用了两个不同的变量。 The latter is just the third element of the @record array. 后者只是@record数组的第三个元素。 Which you have never declared. 您从未声明过。 If you had used use strict you would have gotten the error: 如果您使用use strict ,则会得到以下错误:

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. 在这里,您将$record当作数组引用。

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. 这两个实用程序具有一定的学习曲线,但是它们会阻止您犯简单的错误和错别字,并会减少调试时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM