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

Hello, I have a hash table which i am using to loop though a set of filenames to sub routines. The purpose is to run a sub if a file is not there. there are 6 different files and each need a unique action to be triggered based on the files existence. The problem is that the condition is failing. OK enough talk here is the code

%FileToFunction = ( "$file1", 'emailalert1', "$file2", 'emailalert2', +"$file3", 'emailalert3', "$file4", 'emailalert4', "$file5", 'emailale +rt5', "$file6",'emailalert6' ); foreach my $key ( keys %FileToFunction ) { my $value = $FileToFunction{$key}; print "checking $path$key\n\n"; if (-e "$path$key") { print " it exists $path$key\n\n"; print " found ....: $value\n\n"; } else { print " could not find file $path$key generating alert running +sub for $value\n\n\n"; &$value; } }

Replies are listed 'Best First'.
Re: file check not working
by toolic (Bishop) on Oct 07, 2014 at 12:39 UTC
    Is $path relative or absolute? If relative, maybe you are running your code from the wrong directory. Show us some output.

      thanks. $path is declared. and the filename is a combination of variables.

      my $path = "/home/jose_m/"; my $extension = `date +%Y%m%d.csv`; my $file1 = ("longname_of_file.$extension");

        Are you using warnings or run your script using -w?

        If so, Perl already tells you what goes wrong:

        > perl -wle 'my $f=`date +%Y%m%d.csv`; open my $fh, "<", $f' Unsuccessful open on filename containing newline at -e line 1.

        Personally, I would avoid calling a shell just to run date. Use POSIX::strftime instead:

        use POSIX 'strftime'; my $extension= strftime( '%Y%m%d.csv', localtime ); ...
Re: file check not working
by Corion (Patriarch) on Oct 07, 2014 at 12:34 UTC

    So, how does the file check fail?

    Have you printed "$path$key" to check that it contains what you think it should contain?

Re: file check not working
by jellisii2 (Hermit) on Oct 07, 2014 at 15:05 UTC
    A bit on the outside of this problem, but I highly recommend using File::Spec for building pathnames. It takes a lot of screwyness out of it.