Beeblbrox
Beeblbrox

Reputation: 351

Efficient method to identify a filenames extension when the non-extension name is known

    my $cover="/******/gamebooks/Accounts/$Author/MyBooks/$Book/images/cover/cover.jpg";
if(-e $cover){
    $cover=$uri->encode("https://fightingfantasy.net/gamebooks/Accounts/$Author/MyBooks/$Book/images/cover/cover.jpg");
}
else{
    # print "$cover not found";
    $cover="$perl_scriptlocation/resources/images/beholder.jpg";
}

This is my code at the moment - the directory will have 1 file in it named cover. -the extension will be any valid graphical format commonly displayed by browsers. I could do a directory listing, strip out the results containing the parent and child nodes and use the remaining result but it seems an extremely verbose way of doing it... does anyone have a quicker method to do this? I imagine wildcards are in use somehow... Many thanks.

For those interested (thanks to the 1st answer) my final solution isthis:

    my $coverbase="/******/gamebooks/Accounts/$Author/MyBooks/$Book/images/cover/cover";
    my $cover = glob qq("${coverbase}.*");

    if(-e $cover){
        $cover=~/.*\/(.*)/i;
        $coverfile=$1;
        $cover=$uri->encode("https://fightingfantasy.net/gamebooks/Accounts/$Author/MyBooks/$Book/images/cover/$coverfile");
    }
    else{
        # print "$cover not found";
        $cover="$perl_scriptlocation/resources/images/beholder.jpg";
    }

Which is a lot more satisfying than the only option I had before I knew about glob many thanks (yes I know it could be stripped by 2 or 3 lines still with some elegance but I don't have that yet!)

Upvotes: 1

Views: 38

Answers (1)

Steffen Ullrich
Steffen Ullrich

Reputation: 123380

I'm not sure if I really understand your question. But I assume you have the basename (e.g. "picture") and want to have the name with extension assuming that such a file exists (e.g. "picture.jpg", "picture.png" ..). In this case glob would help:

  my ($file) = glob("$basename.*") or die "no such file exists";

Upvotes: 4

Related Questions