Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

file

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?

like image 956
Lazer Avatar asked Oct 15 '10 07:10

Lazer


People also ask

How do I check file extensions?

Right-click the file. Select the Properties option. In the Properties window, similar to what is shown below, see the Type of file entry, which is the file type and extension.

What is the extension for Perl files?

A file with . pl extension is a Perl Script file that is a scripting language.

What is the extension of this file?

The extension is a three- or four-letter abbreviation that signifies the file type. For example, in letter. docx the filename is letter and the extension is docx. Extensions are important because they tell your computer what icon to use for the file, and what application can open the file.

How do I find the program name in Perl?

The name of the running program can be found in the $0 variable: print $0; man perlvar for other special variables. Sometimes the running program will not be the pl file, but a batch job that loaded and ran the pl file.


2 Answers

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
like image 67
Dave Cross Avatar answered Oct 14 '22 04:10

Dave Cross


Another solution is to make use of File::Type which determines the type of binary file.

use strict;
use warnings;

use File::Type;

my $file      = '/path/to/file.ext';
my $ft        = File::Type->new();
my $file_type = $ft->mime_type($file);

if ( $file_type eq 'application/octet-stream' ) {
    # possibly a text file
}
elsif ( $file_type eq 'application/zip' ) {
    # file is a zip archive
}

This way, you do not have to deal with missing/wrong extensions.

like image 33
Alan Haggai Alavi Avatar answered Oct 14 '22 02:10

Alan Haggai Alavi