Arrays and Checking if Files Exist: Learn Perl By Doing It, Part 4

A tutorial on using arrays in Perl and checking if files exist. Perl is totally excellent for doing stuff involving large numbers of files. Once you know Perl, you'll never need to sit there renaming or moving large numbers of files by hand. Of course you need a certain sort of laziness -- it's better to spend fifteen minutes writing a Perl script than to spend an hour renaming files by hand, unless you love hard, meaningless work.



 
use strict;
use warnings;

$|=1;

sub main {

    # An array of file names. Note the "@"" for array
    my @files = (
        'C:tutorialperlprojectslogo.png',
        'C:tutorialperlprojectsindex.html',
        'C:tutorialperlprojectsmissing.txt',
    );

    # foreach loops through the array, setting the loop
    # variable ($file in this case) to each value in turn.
    
    foreach my $file (@files) {
        
        # -f tests if a file exists.
        if ( -f $file ) {
            print "Found file: $file\n";
        }
        else {
            print "File not found: $file\n";
        }
    }

}

main();