运行我的Perl脚本时出现未初始化的错误

时间:2019-03-08 18:06:28

标签: perl variables

我将第一个参数输入为“ -d”,第二个参数是目录,只要它是有效的目录名即可。

下面是我的代码片段:

first x

我正在尝试返回所有文件名,文件大小,文件所有者和组所有者的列表。当我执行脚本时,它返回文件名,但是在大小和所有者上却出现错误。具体错误是

x

我不确定为什么会说明amountvoucherID userID 11 10 12 10 12 11 变量未初始化

1 个答案:

答案 0 :(得分:2)

未初始化也可以表示已初始化为undef

stat-X运算符返回undef并在错误时设置$!。让我们添加此错误检查。同时,我还将stat系统调用的数量从每个文件2 + 2减少到每个文件1。

if ($ARGV[0] eq "-d") {
    die("Usage\n") if @ARGV < 2;

    my $dir_qfn = $ARGV[1];
    opendir(my $dh, $dir_qfn)
        or die("Can't open dir \"$dir_qfn\": $!\n");

    my @rows;
    while (my $fn = readdir($dh)) {
        next if substr($fn, 0, 1) eq '.';

        my ($size, $gid, $group);
        if (my @stats = stat($fn)) {
            $size  = $stats[7];
            $gid   = $stats[5];
            $group = getgrgid($gid);
        } else {
            warn("Can't stat \"$fn\": $!\n");
            $size  = '???';
            $gid   = '???';
            $group = '???';
        }

        push @rows, [ $fn, $size, $gid, $group ];
    }

    # Print rows here.
    # By having all the data in an array,
    # you can figure out how wide to make the columns.
}

那只是代码的清理版本。我实际上尚未修复错误。但是,由于它现在具有错误检查功能,因此我们可以看到问题所在。运行该程序将为我们提供每个文件名No such file or directory!那是因为您要在当前工作目录中查找文件名,而不是在所属目录中。

要解决此问题,只需替换

if (my @stats = stat($fn)) {
...
    warn("Can't stat \"$fn\": $!\n");

使用

 my $qfn = $dir_qfn . '/' . $fn;
 if (my @stats = stat($qfn)) {
...
    warn("Can't stat \"$qfn\": $!\n");
相关问题