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

I am trying to read in all files from a directory that begin with 4 numbers. They are all HTML pages that I want to make links out of. I am not sure how to differentiate the files based on this info. Here is where I am at so far. Sorry if the code is juvenile, but I am new to Perl and haven't quite got the full grasp on it.

my $directory = 'Where/the/directory/is'; opendir(DIR,$directory); my @files = grep { $_ ne '.' && $_ ne '..' }readdir DIR; closedir(DIR); foreach(@files) { print "<A HREF='$_'>$_</A>"; print "<BR>"; }
Any help would be appreciated...
Prince99

Replies are listed 'Best First'.
Re: finding specific files
by turnstep (Parson) on Feb 26, 2001 at 21:01 UTC
    You can also use a regular expression. You were almost there with the code you had. Here's a slight rewrite:
    my $mydir = 'Where/the/directory/is'; opendir (MYDIR, $mydir) or die "Could not opendir $mydir: $!\n"; my @numfiles = grep { /^\d{4}.*\.html$/} readdir MYDIR; closedir(MYDIR); print "<UL>\n"; for (@numfiles) { print qq! <LI><A HREF="$_">$_</A></LI>\n!; } print "</UL>\n";

    Quick notes:

    • Always check the return of your opens and opendirs. There is no point in the script continuing if they fail.
    • The regular expression in this case matches exactly 4 digits "\d{4}" at the very start of the string "^" followed by anything ".*" and ending in 'dot-html' at the very end of the string "\.html$"
    • If your HTML has double quotes, you can make them without any problems by using an alternative quoting character ("!" in this case) with the qq operator. See the section entitled "Quote and Quote-like Operators" in perldoc perlop.
    • Using <LI> is a quick and easy way to create a nice formatted list - like this one! :)
Re: finding specific files
by merlyn (Sage) on Feb 26, 2001 at 20:52 UTC
Re: finding specific files
by thealienz1 (Pilgrim) on Feb 26, 2001 at 21:36 UTC

    I am going to try to do a weird one now...

    use File::Find; find(sub {if(/^\d{4}.*\.html$/){print qq!<A HREF="$_">$_</A><BR>!;}}, +"/usr/html/");

    Warning I am just doing this to see if I can cut down code... I am not claiming to be an expert or anythign... but if it works... YIPPEEE

    I am the first overweight, very tall munchkin... be very amazed.
Re: finding specific files
by Anonymous Monk on Feb 26, 2001 at 21:44 UTC
    Thank you all for your help. It is greatly appreciated. Maybe one of these days I will be wise enough to post an answer for someone else instead of always asking for help. Thanks again. Prince99