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

Hi,

I need to find out an efficient way, in Perl , of knowing the file format looking at one link.

For example,
given the link 'link1' to file 'file1.jpg'. Looking at that link I need to know that the target file is in format jpg.

Does anyone knows how to do that?
It has to be efficient because I will need to do it repeatedly and fast. I would prefer is the solution cames in default modules.

Thanks in advance,
SHMF
  • Comment on Determine target file format looking at one link

Replies are listed 'Best First'.
Re: Determine target file format looking at one link
by Anonymous Monk on Jul 31, 2008 at 10:01 UTC
    File::MMagic
    #!/usr/bin/perl -- use strict; use warnings; my $file = 'test.png' ; # must exist my $fileL = 'test.link'; # will be created/removed checkit( $file ); warn 'Linking ', link( $file, $fileL ); checkit( $fileL ); warn 'UnLinking ', unlink( $fileL ); sub checkit { use File::MMagic; my $mm = new File::MMagic; # use internal magic file print "Checking $_[0] => ", $mm->checktype_filename( $_[0]),$/; } __END__ Checking test.png => image/png Linking 1 at file.mmagic.check.pl line 12. Checking test.link => image/png UnLinking 1 at file.mmagic.check.pl line 16.
Re: Determine target file format looking at one link
by dHarry (Abbot) on Jul 31, 2008 at 09:30 UTC

    What exactly do you mean? Do you want to inspect the link name and derrive from the file extension (e.g. jpg/jpeg) the type of file you're dealing with. Or are you opening the link and can you inspect the file content?

    Update: See How do I post a question effectively?

Re: Determine target file format looking at one link
by moritz (Cardinal) on Jul 31, 2008 at 09:58 UTC
    What kind of link are you talking about? symbolic links on unixish file systems?? Hyper links on web pages?

    And how do you want to determine the type? Just by looking at the extension? Or by looking into the file?

    Also try Super Search, and the perl documentation.

      I'm sorry I didn't specify correctly my problem.

      I'm talking about symbolic links, and I want to determine the type just by looking at the extension.

      (I don't mind looking into the file but I need the fastest way and I have the file extension in target file, so I think it would be better to use it...)
      Im working in linux.

      Thanks
        I guess you're looking for readlink. A match for /\.jpe?g$/i should do the rest. However, if you cannot trust the suffix or if you are going for a more robust program, you should give the File::MMagic module a try.
        I don't know if there's a pure perl solution, but you can install the program chase and parse its output in perl. Getting the extension should be a simple matter of regexes or split.