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

If any one can offer some insight please do.

What I want to do is scan a dir and find the file with the biggest
name ( Example 1.txt, 2.txt ), then print that to the browser.

$greatest = -1;
opendir "/data", DIR || die "no open data";
while($file = readdir DIR) {$greatest = $file if $file gt $greatest;}
closedir DIR;

print "Content-type: text/html\n\n";


open (DATA, "<$greatest") || die "poop";
@array = <DATA>;
foreach $item (@array) {print $item};

close (DATA);

Replies are listed 'Best First'.
Re: Argh
by athomason (Curate) on Oct 22, 2000 at 10:32 UTC
    I'm assuming that by "biggest name", you mean longest name. In that case, your problem is with $file gt $greatest. This does a string comparison of those two scalars, which is not what you want. Instead, you want to compare the length of the scalars. Do that with length($file) > length($greatest).

    More generally, I'd go with something like this:

    #!perl -w use strict; use CGI ":standard"; my $longest = ""; my $dir = '/data'; opendir DIR, $dir or die "Couldn't readdir $dir"; while(my $file = readdir DIR) { print "'$longest'\n"; $longest = $file if length($file) > length($longest); } closedir DIR; print header, start_html("Longest filename"), "Longest filename in '$dir' is '$longest', which has ", length($longest), ' characters.', end_html;
Re: Argh
by chromatic (Archbishop) on Oct 23, 2000 at 05:32 UTC
    Assuming you're doing a numerical comparison on the first part of the filename, you want code rather more like this:
    my ($greatest, $gnum) = ('', 0); while($file = readdir DIR) { (my $fnum = $file) =~ /^(\d+)\./; next unless $fnum > $gnum; $gnum = $fnum; $greatest = $file; }
    There's room for more polish, but the general idea is there.
Re: Argh
by AgentM (Curate) on Oct 22, 2000 at 10:42 UTC
    ^¬HTean the file with the biggest number (which is poorly explained but is consistent with the example and code given), you should split off the file suffix and compare the numbers. Now that I look at it, I don't see your problem...perhaps if you explain your difficulty....but you should strip the suffix off anyway since you don't need it. (Also, you should use CGI if you didn't and optimize your file-to-stdout routine with a while loop (user will see file faster).)
    AgentM Systems nor Nasca Enterprises nor Bone::Easy nor Macperl is responsible for the comments made by AgentM. Remember, you can build any logical system with NOR.