Search code examples
perlfile

How can I check the extension of a file using Perl?


To my perl script, a file is passed as an arguement. The file can be a .txt file or a .zip file containing the .txt file.

I want to write code that looks something like this

if ($file is a zip) {

    unzip $file
    $file =~ s/zip$/txt/;
}

One way to check the extension is to do a split on . and then match the last result in the array (returned by split).

Is there some better way?


Solution

  • You can use File::Basename for this.

    #!/usr/bin/perl
    
    use 5.010;
    use strict;
    use warnings;
    
    use File::Basename;
    
    my @exts = qw(.txt .zip);
    
    while (my $file = <DATA>) {
      chomp $file;
      my ($name, $dir, $ext) = fileparse($file, @exts);
    
      given ($ext) {
        when ('.txt') {
          say "$file is a text file";
        }
        when ('.zip') {
          say "$file is a zip file";
        }
        default {
          say "$file is an unknown file type";
        }
      }
    }
    
    __DATA__
    file.txt
    file.zip
    file.pl
    

    Running this gives:

    $ ./files 
    file.txt is a text file
    file.zip is a zip file
    file.pl is an unknown file type