in reply to Perl Tk: opening a file in its original format

What you want to do is commonly called "launch an external program and display a file through it", or at least that's how I understand your question.

If you're using Windows, it is really easy to launch whatever program the user configured for whatever kind of file you want to "display":

my @args = ("start",$file,$file); for (@args) { # Apply smart-ish double quotes if (/ /) { $_ = qq{"$_"}; } }; system(@args) == 0 or warn "Couldn't launch '$file' : $!/$?/$^E";

Under Unix, it is much harder to know what program the user wants to be launched and you will likely want to make this an option in a config file or in the environment. The idea still remains the same though.

Updated: Fixed missing closing brace, spotted by rcseege

Replies are listed 'Best First'.
Re^2: Perl Tk: opening a file in its original format
by Fletch (Bishop) on Oct 17, 2005 at 14:25 UTC
    Under Unix, it is much harder to know what program the user wants to be launched and you will likely want to make this an option in a config file or in the environment. The idea still remains the same though.

    For values of "Unix" near "OS X" you can use the open command which functions similarly to start (opening the file in the associated application).

Re^2: Perl Tk: opening a file in its original format
by FM (Acolyte) on Oct 18, 2005 at 03:16 UTC
    I want to thank you both very much for your help. However, since I am not that familiar with Perl yet, I would love for Corion to explain to me why we need "start" and then two $file in the array? What does the qq stands for? Hope to hear from you. FM

      Let's look at my code:

      Starting at the top, I assemble the command and parameter list in the @args array. The start command on Win32 takes the command to run as the first or second parameter, depending no the shell/OS. command.com takes it as the first parameter while cmd.exe takes it as the second parameter. So you can consider it as an old habit to put the file twice there. Typing help start in cmd.exe will tell you lots about other options.

      my @args = ("start",$file,$file);

      Next, I put all parameters that have spaces in them into double quotes. This is a very crude mechanism, because it doesn't pay attention to other characters that might confuse the shell, like ?,&,| or %. To prepend and append a double quote, I use alternative double quotes by using the qq quoting operator, see perlop or perldoc perlop, in case the link doesn't work.

      for (@args) { # Apply smart-ish double quotes if (/ /) { $_ = qq{"$_"}; } };

      Two alternative ways to achieve the same quoting would be :

      $_ = '"' . $_ . '"'; # or $_ = "\"$_\"";

      So I think you should see why I prefer $_ = qq{"$_"} over that.

      The only thing that remains is to hand the parameter list to the shell:

      system(@args) == 0 or warn "Couldn't launch '$file' : $!/$?/$^E";