【问题标题】:When referencing two variables perl returns Use of uninitialized value当引用两个变量时 perl 返回使用未初始化的值
【发布时间】:2013-11-29 23:39:54
【问题描述】:

我有两个目录,一个目录是文件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 行调用和 main::playnice(HG111_1_001.txt 在第 21 行调用

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

#!/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?';
}

【问题讨论】:

    标签: perl windows-7 strawberry-perl


    【解决方案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 函数。

    你也应该:

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

    【讨论】:

    • 您介意提供答案的非简洁版本吗?
    • 你只用一个参数调用你的 playnice 函数。这就是 $file2 未定义的原因
    • 我好像发现了你的想法
    • 问题不在于如何在 playnice 函数中检索参数,而在于如何将参数传递给函数。你应该用类似这样的方式调用你的函数: playnice($arg1,$arg2)
    • @user3050913 - Pierre 不是字面意思建议playnice($arg1, $arg2),而是表明您需要将两个(初始化的)arguments 传递给您的playnice子程序。在程序的顶部,考虑my $file1 = ''; my $file2 = '';,然后是playnice($file1, $file2);
    猜你喜欢
    • 2018-10-08
    • 2013-08-25
    • 1970-01-01
    • 2011-07-19
    • 1970-01-01
    • 2016-09-25
    • 2013-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多