jriggs420 has asked for the wisdom of the Perl Monks concerning the following question:

#!/usr/bin/perl -w use Cwd; opendir(DIR, "."); @files = readdir(DIR); closedir(DIR); my $file; my $i=0; foreach $file (@files) { if ($file=~ /^(rs|rp|re|tv|pr|do)[0-9]{7}$/){$job=$file; print "$job\n";}#prints $job's value no problem if (undef $job) {print "Job file not found! Check directory!\n +";exit;}#passes this $cwd = cwd(); #my $job=$job;#just trying some stuff-- print $job."\n";#blank print "$cwd\nrand can only be used in a 'projects' folder!\n"; if ($cwd !~ /\/script\/projects\/$job/){exit;}
I get the use of uninitialized variable in the last line ($job) which doesn't make sense to me because I call it later on in the script, and it is there! Any ideas? TIA

Replies are listed 'Best First'.
Re: foreach not a global variable?
by dragonchild (Archbishop) on Apr 21, 2006 at 20:23 UTC
    if ( ! defined $job ) { ... }
    undef() is a function that sets any variable passed to it to undef.

    My criteria for good software:
    1. Does it work?
    2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?
Re: foreach not a global variable?
by GrandFather (Saint) on Apr 21, 2006 at 22:46 UTC

    undef is a function that sets a variable to undefined as already pointed out by DragonChild. What you are after is defined which tests to see if a variable is defined so the code you want is:

    if (! defined $job) {#passes this print "Job file not found! Check directory!\n";exit; }

    However there is another subtle thing going on here that you should be aware of. You declare my $file outside a for loop which uses $file as the loop variable. Take particular note that the contents of $file are only valid inside the loop and that $file is an alias to the items in @files that the loop iterates over. This is not causing a problem in the code you show, but is important to remember. Especially because when you change the contents of a loop variable you are actually changing element of the list that the loop variable is currently aliased to. In you code that means that changing the contents of $file inside the loop changes the contents of an element of @files.


    DWIM is Perl's answer to Gödel
Re: foreach not a global variable?
by jwkrahn (Abbot) on Apr 21, 2006 at 22:18 UTC
    You probably want something like:
    #!/usr/bin/perl -w use strict; use Cwd; my $dir = '/script/projects'; opendir DIR, $dir or die "Cannot open directory '$dir' $!"; my ( $job ) = grep /^(?:r[spe]|tv|pr|do)\d{7}$/, readdir DIR; defined $job or die "Job file not found! Check directory!\n"; # etc.