Sunday, November 22, 2009

Globbing a directory in perl

To glob a directory is very simple in Perl.
We just have to use these three lines of code...

#!/usr/bin/perl -w

@files =
# FILEPATH can be like *
# for all html files it can be /var/doc/*.html

foreach $filename (@files){
open FILE, "<$filename" or die $!;
# do my 50 things
close FILE
}

1 comment:

  1. If you just want to glob the entire directory's first level file contents, you could do this:

    perl -le '@ARGV = grep { -f $_ } <$ARGV[0]/*> ; @files = <>; use Data::Dumper; print Dumper \@files;'

    where your first command line argument is the directory whose contents you want to slurp.

    ReplyDelete