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

Hi, Firstly apologies for the poor title. I am having a few problems with the below script. @row contains a list of strings which are associated with xml files. However, some of the files no longer exist. If the file does not exist i want to skip it and try the next file without the script dying.
foreach $id (@row) { #if ($id != 113) { print "id = $id"; use Fcntl 'O_RDWR'; tie @array, 'Tie::File', "../XML/$id.xml", mode => O_RDWR; splice @array, 2, 0, "<database_id=\"gl:redunant\">"; untie @array;
So if file does not exist skip. Is this possible? Thanks

Replies are listed 'Best First'.
Re: if file does not exist
by Aristotle (Chancellor) on Nov 21, 2005 at 17:17 UTC

    You test whether a file exists using -e. Together with some cleanup, that means:

    use Fcntl 'O_RDWR'; for my $id ( @row ) { my $fname = "../XML/$id.xml"; next if not -e $fname; tie my @array, 'Tie::File', $fname, mode => O_RDWR; splice @array, 2, 0, "<database_id=\"gl:redunant\">"; untie @array; }

    Makeshifts last the longest.

      thanks for your help
Re: if file does not exist
by philcrow (Priest) on Nov 21, 2005 at 17:19 UTC
    Try:
    next unless ( -e "../XML/$id.xml" );
    as the frist line of the loop.

    Phil

Re: if file does not exist
by jdhedden (Deacon) on Nov 21, 2005 at 17:18 UTC
    Just add this to the start of the loop:
    next if (! -f "../XML/$id.xml");
    Updata: Aristotle's solution is a tad better using -e instead of -f.

    Remember: There's always one more bug.

      I think your solution is actually better because -e will return true for a directory too. So-

      next if not -f $fname; # or the somewhat too dense warn "$fname is not a file" and next unless -f $fname;

Re: if file does not exist
by holli (Abbot) on Nov 21, 2005 at 17:18 UTC
    foreach $id (@row) { if ( -e "../XML/$id.xml" ) { #... } }


    holli, /regexed monk/