Belgin Fish
Belgin Fish

Reputation: 19827

Perl 'if' statement

Right now, I have the following Perl code

my $tmpl1="download1_video.html"
 if $file->{file_name}=~/\.(avi|divx|mkv|flv|mp4|wmv)$/i;
$tmpl1||="download1.html";

so it's checking to see if the file is a video, and if so it directs it to the certain page. Although I'm just wondering how I can add another if statement in there to check if the extension is .mp3, and if so direct it to download1_audio.html.

Upvotes: 1

Views: 430

Answers (3)

Axeman
Axeman

Reputation: 29844

Having just been burnt by this, I must advise you against declaring a variable with a conditional modifier. If the condition does not hold true, it runs no part of the other clause, which means that you are not declaring $tmpl1, but since it's already passed strict, it allows you to assign to an undefined position in memory.

There is a safer way to do what your predecessor is doing here, that can yet illustrate a solution.

my $tmpl1
    = $file->{file_name} =~ /\.(avi|divx|mkv|flv|mp4|wmv)$/i 
        ? 'download1_video.html'
        : $file->{file_name} =~ m/\.mp3$/i
            ? 'download1_audio.html'
            : 'download1.html'
    ;

Thus,

  1. $tmpl1 is always declared
  2. $tmpl1 is always assigned a value

Upvotes: 1

Brian Roach
Brian Roach

Reputation: 76888

if ($file->{file_name} =~ /\.(avi|divx|mkv|flv|mp4|mp3|wmv)$/i )
{
    if ($1 eq "mp3")
    {
        # mp3 stuff
    }
    elsif ($1 eq "mp4")
    {
       # mp4 stuff
    }
    else
    {
       # all other file types
    }
}
else
{
    # It didn't match
}

A fancier way would be to create a hash keyed by your file types in advance with the info you needed for your next page; the filename I guess?

my %pageHash = ( "mp3" => "mp3Page.html", "divx" => "divxPage.html", ... );
...
$file->{file_name} =~ /\.(.*)$/i;
if (exists $pageHash{$1})
{
     $page = $pageHash{$1};
}
else
{
     # unknown file extension 
}

Upvotes: 4

Arunmu
Arunmu

Reputation: 6901

if ( $file->{file_name} =~  m/\.(avi|divx|mkv|flv|mp4|wmv)$/i ){
     ## Download video
}
elsif($file->{file_name} =~  m/\.(mp3)$/i){
     ## Download Audio
}

Is this what you needed ?

Upvotes: 5

Related Questions