引用两个变量perl时返回使用未初始化的值

时间:2013-11-29 23:39:55

标签: perl windows-7 strawberry-perl

我在一个目录中有两个目录是文件HG111_1_001.txt,在另一个目录中是HG111_2_001.txt。这两个文件需要通过一组命令(sub single和sub double)处理,然后作为一对返回到sub playnice。我遇到的问题如下:

代码返回以下不明确的警告: 在C:\ Users \ prl \ tools.pl第52行的字符串中使用未初始化的值$ file2。 这将是最终的印刷品。

启用Carp时,此错误表示: main :: playnice(HG111_2_001.txt在第37行和第37行调用) main :: playnice(第21行调用HG111_1_001.txt

这些是与我将值传递给子时相对应的行。

#!/usr/bin/perl -w

use strict;
use warnings;

my $dirname  = 'C:\Users\prl';
my $dirname2 = 'C:\Users\prl\1';

my $file1;
my $file2;

#Read Directory and find first file
opendir( D, $dirname2 ) or die "can't opendir $dirname: $!";
while ( $file2 = readdir(D) ) {

    next unless $file2 =~ m/^HG111_1_0/;

    my $path2 = "$dirname2\\$file2";
    single( $file2, $path2 );
    playnice($file2);
}

#Pass to first sub
sub single {
    my $file2 = shift;
    my $path2 = shift;
    print "$path2\n";
    print "$file2\n";
}

opendir( DIR, $dirname ) or die "can't opendir $dirname: $!";
while ( $file1 = readdir(DIR) ) {
    next unless $file1 =~ m/^HG111_2_0/;
    my $path2 = "$dirname\\$file1";

    double( $file1, $path2 );
    playnice($file1);

}

sub double {
    my $file1 = shift;
    my $path1 = shift;
    print "$path1\n";
    print "$file1\n";
}

sub playnice {
    my $file1 = shift;
    my $file2 = shift;

    print "$file1", "$file2", "\n", 'orked?';
}

1 个答案:

答案 0 :(得分:1)

你只将一个参数传递给你的playnice函数......

见这个简单的例子:

sub playnice {
  my ($f1,$f2) = @_;
  print "$f1 $f2\n";
}

# your program: wrong, $f2 is undef
playnice('foo'); # one argument

# what it should do
playnice('foo','bar') # two argument

现在您必须编辑代码并使用两个参数调用playnice函数。

你也应该:

  • 考虑将所有子程序放在同一个地方(在 程序的开始/结束);
  • 清楚地告诉我们这个计划的目的;
  • 清理代码(添加缩进和注释)