Perl Strawberry: How to run a perl script by clicking

2.2k views Asked by At

I'm working on Windows 7 and I have installed Strawberry. I would like to run a perl skript (test.pl):

open OUTPUT, ">test.txt";
print OUTPUT "This is a test\n";

by just clicking on the file or redirect with left mouse click to Perl-program (open with/perl.exe). When I do this a console opens for less than a second and disappears but the file test.txt is not created. If I go to the MS command and enter

> C:\myplace>perl test.pl  

it works. I never had this experience before (WinXP, other Windows 7 PC with ActivePerl and Windows 8 with strawberry). I would be very happy if somebody could give me a hint how to solve this problem.

2

There are 2 answers

1
amon On BEST ANSWER

There are two problems here:

  1. Creating the file where you want it. When double-clicking a perl script to launch it, it is not executed in the context of the folder you have opened in Explorer. If you want to specify an explicit context, do the following near the top of your script:

    use FindBin;  # This is a module that finds the location of your script
    BEGIN { chdir $FindBin::Bin }  # set context to that directory.
    

    When you then create a new file without an aboslute path, the path is considered relative to that directory.

    You do not have the problem when running the script from the command line, because you have specified the correct path. But if you run it from C:\ like

    C:\> perl myplace/test.pl
    

    then you have created the file in C\test.txt. The FindBin solution fixes this.

  2. When running a script by double-clicking it, the command line exits before you can inspect the output. This “problem” is shared by all programming languages on Windows. You can force the window to stay open by waiting for some input. You can either do

    system("PAUSE");  # not portable to non-Windows!
    

    or

    warn "Press enter to exit...\n";
    <STDIN>;  # Read a line from the command line and discard it.
              # Feels akward when launching from the command line
    

    to wait until an Enter ⏎ is pressed .

    The other solution is to always use the command line for your scripts, which is what I'd actually suggest.

2
mpapec On

Check what is your script executing folder, as it might differ from C:\myplace

use Cwd;
print getcwd();
sleep 7;