When referencing two variables perl returns Use of uninitialized value

127 views Asked by At

I have two directories in one directory is file HG111_1_001.txt, in the other directory is HG111_2_001.txt. This two files need to processed through a set of commands (sub single and sub double) and then brought back as a pair to sub playnice. The issue I'm having is as follows:

The code returns the following ambiguous warning: Use of uninitialized value $file2 in string at C:\Users\prl\tools.pl line 52. This would be the final print line.

When use Carp is enabled this error indicates that: main::playnice(HG111_2_001.txt called at line 37 and main::playnice(HG111_1_001.txt called at line 21

Where these are the lines corresponding to when I pass the value to the sub.

#!/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

There are 1 answers

8
Pierre On BEST ANSWER

you pass only one argument to your playnice function...

See this simple example:

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

now you have to edit your code and call the playnice function with two arguments.

also you should:

  • consider putting all your subroutines at the same place (at the beginning/end of the program);
  • tell us clearly the purpose of this program;
  • clean your code (add indentation and comments)