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

I need to take a decission based on the file type. As i am new to PERL i am not sure how to do it. So i have a .txt file and a .csv file, how do i test the file extension.

Replies are listed 'Best First'.
Re: how to Check file type?
by Your Mother (Archbishop) on Dec 02, 2010 at 16:09 UTC

    An approach might include MIME::Types + File::Basename. That said, you need to remember the extensions do not guarantee content/type-

    mv pr0n.jpg annual-report.xls
      What the heck is this adult content doing in my spreadsheet!?!  ;-)
      
      

      s''(q.S:$/9=(T1';s;(..)(..);$..=substr+crypt($1,$2),2,3;eg;print$..$/
Re: how to Check file type?
by chrestomanci (Priest) on Dec 02, 2010 at 16:14 UTC

    If you just want to get the extension of filename, then use File::Basename

    eg:

    use File::Basename; ($name,$path,$suffix) = fileparse($fullname,@suffixlist); $name = fileparse($fullname,@suffixlist);

    The second argument of fileparse is either a literal list of acceptable extensions, or a regular expression, that will match acceptable extensions, so for normal DOS style extensions, you would write:

    $name,$path,$suffix) = fileparse($fullname,qr/\..*/);

    If you wan't to find out what type a file is, and you can't use, or don't trust the filename, then something like the unix file utility may be helpful. It reads the file contents, and attempts to guess the file type from what it finds. In my experience it is usually correct.

Re: how to Check file type?
by ChuckularOne (Prior) on Dec 02, 2010 at 19:07 UTC
    Another way to grab the extension is to put the split name in an array and pop the last element.
    #!/usr/bin/perl -w my $filename = "this.is.my.filename.txt"; my @bits = split /\./, $filename; print pop @bits;

      Saving the whole array and then popping off the last element uses up lines and adds variables. I'd rather wrap the split in parentheses and reference the last element.

      my $suffix = ( split /\./, $filename )[-1];

      The only danger is that if the only reason you're getting the suffix is to print it, you need more parentheses to prevent print from thinking a subset of the expression is its argument list:

      print ( split /\./, $filename )[-1]; # wrong print (( split /\./, $filename )[-1]); # unpleasant

      As Occam said: Entia non sunt multiplicanda praeter necessitatem.

        Thanks, that was basically (however inelegantly) what I was trying to accomplish. Printing was just for demonstration purposes.
Re: how to Check file type?
by Anonymous Monk on Dec 02, 2010 at 16:13 UTC

    Most people just look at the letters following the last '.' and call it a day.

    You want to look for (ie: regex) a literal '.' (use a backslash), plus up to three characters that are not dots, then the end of string. And capture those characters.