Perl

Perl basics for beginners (on Windows)

August 7th, 2010    3 Comments

I've been writing some Perl again recently. The scripts I've been writing have all been sitting on a Solaris server to which I've been connecting remotely. But today my connection was super slow (thanks Sky Broadband) so I decided to work locally on my PC for a change.

This meant getting Perl working on my laptop. It's pretty easy. So I thought I'd blog the steps involved.

Read on if you want to try writing some Perl but:

  • You don't know how to get Perl set up
  • You don't have access to a server where Perl is already set up
  • You use Windows and you really don't want to become a Linux guru (at least not today)

Xampplogo There are a variety of ways to do this. This is just the way I used a few minutes ago. It uses XAMPP which means that, by the end of the process not only will you have Perl (one of the Ps in "XAMPP"), you'll also have the Apache Web Server, MySQL and PHP. In case you're wondering, the X apparently stands for cross-platform. You might not want all of these right now but, unless you're really tight for disk space, I'd advise getting them anyway. If you're ever going to do any Web development, having this package of technologies on your laptop, ready to switch on with the click of a button, is fantastically useful.

So here we go:

  1. Browse to http://www.apachefriends.org/en/xampp-windows.html
  2. Scroll down the page to the download section for XAMPP for Windows.
  3. Click the link for the EXE file (content description: "Self-extracting RAR archive").
  4. Once downloaded, double-click the xampp-win32-n.n.n.exe file and confirm you want to run it.
  5. In the XAMPP for Windows dialog box, change the destination folder if required.

    The installer installs XAMPP in an xampp directory within the destination you specify. So if you leave the destination at C:\ then you'll get a C:\xampp directory. I prefer to install things in D:\programs, so I changed the destination to this.

    xampp-install

  6. Click Install.

    From here on it's just a case of following the on-screen instructions.

  7. After XAMPP is installed,  open the Windows Control Panel and double-click System.
  8. Under Tasks, click Advanced system settings.
  9. In the System Properties dialog box, click Environment Variables.

    systemProperties

    We're going to add the path to Perl to your system's Path environment variable, so that it knows where to find the Perl executable for running Perl programs.

  10. In the Environment Variables dialog box, scroll down the list of system variables and double-click the entry for Path.

    environVariables

  11. In the Edit System Variable dialog box, click in the Variable value field, move the cursor to the end of the text and add a semicolon followed by <destination>\xampp\perl\bin. For example, if you installed xampp in C:\ you would enter

    ;C:\xampp\perl\bin

    In my case, my path to Perl is D:\programs\xampp\perl\bin.

    editSysVariables

  12. Click OK in this and the other two dialog boxes.

    We'll now test that Perl is installed correctly.

  13. Click the Windows button (that is, go to what used to be called the Start menu).

  14. Enter cmd into the search box.

    A command console window opens.

  15. Enter: perl -v

    If everything's working correctly you'll get a message that shows the Perl version that's installed - for example:

    This is perl, v5.10.1

    perl-v

    What this means is that, once you have a Perl script, you'll be able to cd to the directory in the command console and run the script by entering perl myscript.pl.

  16. Close the command console window.

    Now we're going to start doing the interesting stuff: writing a Perl script.

  17. Open you're favourite text editor - for example, Notepad++.

  18. Enter the following:

    #!D:\programs\xampp\perl\bin\perl.exe   
      
    use strict; use warnings;  
     
    print "Hello world!\n"; print "Press Return to exit.\n";  

      
    my $userInput = <>;


    Note: You'll need to change the first line to match the path to perl.exe on your computer.

  19. Save the file as myscript.pl.

  20. Open Windows Explorer and navigate to the folder where you saved the script.

  21. Right-click myscript.pl and choose Open With > Choose Default Program.

  22. In the Open With dialog box, click Browse.

  23. Browse to your perl\bin directory and double-click perl.exe.

  24. In the Open With dialog box, select the check box labelled Always use the selected program to open this kind of file and click OK.

     perlOpenWith

    You've now associated the .pl file name extension with the perl.exe executable. Windows now knows to use perl.exe to run .pl files.

    So let's test it out.

  25. In Windows Explorer, double-click myscript.pl.

  26. A command console window opens to run the script. Our two lines are printed to standard output (in layman's terms they're displayed) and (thanks to $userInput = <>) the script waits for you to enter something before exiting. If you didn't have this line the console window would just close and you wouldn't have time to read what was on the screen.

    helloworld-output

    Job done. From now on you can write Perl scripts in your text editor and run them by just double-clicking the file in Windows Explorer.

So what?

Yeh, okay, so it's just another "Hello world!" program.

But now that you've got Perl set up and you know how to run a program, you can go off and learn to do lots of stuff with Perl.

Me, I'm going off to write a Perl script that will run every half an hour to: parse a table on a "Revision history" Web page within a WebHelp site generated from Madcap Flare, look for new rows in the table (i.e. details of new changes to the WebHelp) and, if it finds any, email the details to a mailing list and then alter the HTML of the Web page adding a style tag to the rows to indicate that the mailing list has been mailed the details.

I hope you find this useful. Drop me a comment to let me know.

Comments

  1. User Gravatar Hamish Blunck said:

    August 8th, 2010 at 11:03 am (#)

    Great post, Alistair. Another one I have used is http://www.activestate.com/activeperl, which works well on Windows.

  2. User Gravatar itauthor said:

    August 9th, 2010 at 7:36 pm (#)

    Raj, you're wrong. All of the above applies to Vista. My laptop runs Vista. All of the above relates to what I did myself on Vista - the screenshots kind of prove this, don't they? In Vista, go to the Windows Control Panel and double-click System. On the left hand side there's a list headed Tasks, with an option "Advanced system settings".

    But thanks for commenting anyway.

  3. User Gravatar itauthor said:

    August 9th, 2010 at 7:37 pm (#)

    Yeh, good call. I used ActivePerl for years and it's another great option.

    Thanks for that Hamish.

Leave a comment

 

Gotchas with running a Perl script as a cron job

August 3rd, 2010    1 Comment

So you've written a Perl script and it runs fine from the command line using a command such as:

perl /home/alistair/scripts/myscript.pl


Great, so now you set up a cron job so that the script will run automatically. For example, let's say you want to run it every Monday morning at 4.20 am:

20 4 * * 1 perl /home/alistair/scripts/myscript.pl

 
However, when this runs it generates the following email:

Your "cron" job on myserver
perl /home/alistair/scripts/myscript.pl

produced the following output:

Can't locate DBI.pm in @INC (@INC contains: /usr/perl5/5.6.1/lib/sun4-solaris-64int /usr/perl5/5.6.1/lib /usr/perl5/site_perl/5.6.1/sun4-solaris-64int /usr/perl5/site_perl/5.6.1 /usr/perl5/site_perl /usr/perl5/vendor_perl/5.6.1/sun4-solaris-64int /usr/perl5/vendor_perl/5.6.1 /usr/perl5/vendor_perl .) at /home/alistair/scripts/myscript.pl line 15.
BEGIN failed--compilation aborted at /home/alistair/scripts/myscript.pl line 15.

 
What this means is that your script uses a Perl module (in this example, DBI.pm) which can't be found. The error message shows all the paths in the @INC list of paths where Perl looks for modules. So, for some reason, Perl found the module when you ran the script, but didn't find the module when cron ran the script as you.

The reason is that cron doesn't run in the same environment that you're using. When you connect to the server, you probably automatically change to your preferred shell (e.g. csh, ksh or bash) and load up a whole set of environment variables. This happens within the startup file – for example, .bashrc or .cshrc. But cron doesn't load up any of this, and it uses sh by default.

To see what's in @INC within your environment use this command:

perl -le 'print for grep {$_ ne q{.}and -d} @INC'

 
And you'll probably notice differences between the output you get and the contents of @INC listed in the error message.

So, to make sure @INC contains the necessary paths in any environment, load it up from within your Perl script. To do this, add something like the following to the top of your Perl script, just after the path to Perl:

BEGIN {
     push @INC,( '/usr/local/lib/perl5/5.8.2/sun4-solaris',
          '/usr/local/lib/perl5/site_perl/5.8.2/sun4-solaris',
          '/usr/local/lib/perl5/site_perl/5.8.0/sun4-solaris',
          '/usr/local/lib/perl5/site_perl/5.6.1/sun4-solaris' );
}


So now Perl will be able to find the missing Perl module. Sorted! Well maybe not.

If you now try running the script from the cron job you may get something like:

Your "cron" job on myserver
perl /home/alistair/scripts/myscript.pl

produced the following output:

ld.so.1: perl: fatal: relocation error: file /usr/local/lib/perl5/site_perl/5.8.0/sun4-solaris/auto/DBI/DBI.so: symbol Perl_PerlIO_stderr: referenced symbol not found Killed


Now it's complaining about not finding something called ld.so.1. The problem here is with your PATH.

On my server, ld.so.1 lives in /usr/lib. You should be able to find out where ld.so.1 is by running:

whereis ld.so.1


/usr/lib isn't exactly an obscure place to look, but it's not in the PATH when the cron job runs. So the easy solution is to explicitly set the contents of the PATH environment variable in the cron job:

20 4 * * 1 PATH=/usr/local/bin:/usr/bin:/usr/sbin:/usr/lib; perl /home/alistair/scripts/myscript.pl


Now, just before the Perl script is run, the PATH gets set to three paths: /usr/local/bin, /usr/bin, /usr/sbin and /usr/lib. The syntax used here is that required by the sh shell in which cron runs.

At last, job done. The script runs and you'll be emailed any output it generates.

Leave a comment



PHP (or Perl) one line if/then/else statements

August 8th, 2009

If you're toggling something between two states in PHP or Perl it's often handy to use an if/then/else one liner.

In pseudocode this goes like this:

<if this evaluates to TRUE> then <parse this> else <parse this>

All you need to do is replace the "then" with a question mark and the "else" with a colon:

<if this evaluates to TRUE> ? <parse this> : <parse this>

For example:

print  $trueOrFalse ? "you're telling the truth" : "you're lying";

Ignore the print command, it's not part of the if/then/else statement, it's just here to do something with the outcome of that statement.

The expression immediately to the left of the question mark is evaluated. The expression between the question mark and the colon is parsed if the expression evaluates to TRUE, otherwise the expression immediately to the right of the colon is parsed. So in the above example, either "you're telling the truth" or "you're lying" is printed, depending on whether $trueOrFalse is ... you guessed it ... TRUE or FALSE.

But perhaps a more common situation is toggling the value assigned to a variable. For example, toggling between TRUE and FALSE:

$trueOrFalse = $trueOrFalse ? FALSE : TRUE;

Here's a practical example of the use of if/then/else one liners. There's two in this chunk of PHP. The scroll box list below the code is the kind of thing this PHP produces.

<div style="overflow:auto; height:100px; width:300px; border:3px groove #DDD; padding:0">
<?php
    $alternateLine = FALSE;
    while($presidentsArray) {
        print "<div style=\"background-color:";
        print $alternateLine ? "#F5F8F9" : "white";
        print "; padding-bottom: 1px\"> &nbsp; &nbsp; <a href=\"someURL\" title=\"This link goes nowhere\">" .
          $presidentsArray['name'] . "</a></div>";
        $alternateLine = $alternateLine ? FALSE : TRUE;
    }
?>
</div>

Leave a comment



Changing your CVS host

February 5th, 2009

What do you do if the host name of your CVS server changes? For example, here’s my case. I checked out a whole lot of CVS modules from the repository while my laptop was on the domain. Now however, thanks to Vista SP1 not playing with an antiquated NT domain, the laptop can’t join the domain so to connect to a server I need to qualify its name with a domain. So, whereas I checked out the modules using the hostname “cvshost”, I now need to use “cvshost.mydomain.co.uk”.

Unfortunately, TortoiseCVS has no way to change the host names for modules you’ve already checked out. WinCVS can, supposedly, do this thanks to a macro. However, WinCVS stubbornly tells me I don’t have Python installed (I do) and therefore won’t let me use macros.

The solution is to just go through all the CVS “Root” files and change the host name. The Root file lives in the CVS directory at each level within a checked out module. This would be a laborious task by hand, but if you have SUA (Microsoft’s Subsystem for UNIX Applications) and Perl installed it’s easy. Just pull up a Korn shell and browse to the directory within which your checked out CVS modules live.

Run the following command.

find . -name 'Root' -print0 | xargs -0 perl -pi -e 's/oldhostname/newhostname/g'

For example, I ran the command:

find . -name 'Root' -print0 | xargs -0 perl -pi -e 's/cvshost/cvshost.mydomain.co.uk/g'

Which changed the Contents of the Root file from:

:pserver:achristie@cvshost:/company/repository

to:

:pserver:achristie@cvshost.mydomain.co.uk:/company/repository

Leave a comment



Setting up the Perl CPAN module installer

October 11th, 2007    2 Comments

perl -MCPAN -e 'install Collection::Module'

is the standard way of installing Perl modules.

The first time you run this you get asked lots of questions. For most of these you can just hit Enter to accept the default. However, you must tell it where to find the modules - i.e. the name of a CPAN mirror site. You can add several, one after the other, so that, if the first one fails, it just tries the next one in the urllist.

You can find a list of URLs at:

http://www.cpan.org/SITES.html

Now common sense might tell you that all you need to do is copy the URL for one of the FTP sites, paste it in and Bob's your uncle. Not so, in some cases, however, because if you're sitting behind a firewall that's fussy about what it allows to be passed via FTP, then you'll have to choose an HTTP URL rather than one of the FTP ones.

If you've already added URLs and got failure messages when you try to install modules, try adding an HTTP one as your first choice site. To do this, go to the CPAN command prompt:

perl -MCPAN -eshell

Once there enter:

o conf

to list your configuration settings. You'll see your urllist. Now enter:

o conf urllist unshift HTTP-URL

This sticks the URL at the top of the list. Depending on the age of your CPAN module and the way it's been set up, you may now have to do:

o conf commit

to make the change permanent, otherwise it will only last for the duration of the interactive session.

Now try installing the module again using:

install Collection::Module

To quit out of the CPAN shell enter:

quit

And if installing using the CPAN installer still fails, you can always just download the package from CPAN and install it manually using the instructions I described recently.

However, if you're somewhere where there's no access to the internet - or the server is locked down to prevent anything being installed from a remote source - you're going to have to use a copy of CPAN that you've downloaded previously onto a DVD or a thumb drive. For more on this have a listen to the Perlcast episode Making My Own CPAN by Brian D Foy.

Leave a comment



^ back to top ^

Page 1 of 3123