Monday, February 12, 2007

Perl Faq

PART I

- How do I delete a file using Perl?
To delete files you use the unlink() function. Here are a few examples of how the unlink() function can be used:

Code:
$cnt = unlink 'a', 'b', 'c';
unlink @goners;
unlink <*.bak>;
unlink("/path/to/file.bak");

- How do I delete a directory using Perl?
To delete a directory you use the rmdir() function. Directories must be empty before they can be deleted.
Code:
rmdir(DIRNAME)



-How do I rename a file or directory using Perl?
To rename a file or directory you use the rename() function.
Code:
rename(OLDNAME,NEWNAME);

-How do I CHMOD a file using Perl?
To CHMOD (set file/folder permissions) you use the chmod() function. Some examples:
Code:
chmod 0755, @executables;
chmod 0644, filename;
$cnt = chmod 0644, 'file1','file2','file3';

-How Can I find Occurences in Lines Between Two Patterns Using Perl?
Assuming the two patterns are START and END you can do something like this:
Code:
open (FILE,"yourfile");
while ( ) {
push(@temp,$1) if (/START(.*?)END/gs);
}
close(FILE);

any occurences of a match will be stored in the @temp array in the above example.


If you just wanted to print the lines that had the two patterns and not worry about what was between the patterns you can do something like this:

Code:
open (FILE,"yourfile");
while ( ) {
print "$_\n" if (/START/ .. /END/);
}
close(FILE);

-How can I know what's causing a 500 Internal Error Message?
When you see the typical "500 Internal Server Error" message it's not much help at understandling what went wrong and is causing the script to crash and burn. To see a much better error message place this code at the beginning of your Perl script, but below the very first line of the script:
Code:
use CGI::Carp qw(fatalsToBrowser);
This will force Perl to display in your browser a more detailed description of what is causing your script to crash.

You should use it when debugging problems but remove it or comment it out once your script is running properly.

If you still get a 500 Internal Server Error after inserting that line just below the first line of your Perl script, which will look something like this:

#!/usr/bin/perl

that generally means the very first line is the wrong path to Perl or there is a syntax error in that line. Make sure the line starts with a number sign, follwed by an exclamation:

#!

and check with your host that you are using the correct path to Perl.

-How Can I See a List of the Perl Modules Installed on My Server?
This short script should work on just about any server to list the Perl modules installed on the server or your hosts server. It might take a moment to run and display so be patient if the list takes a few moments to display in your browser.**
Code:
#!/usr/bin/perl -w
use CGI;
use strict;
use File::Find;
my %list;
my $q = new CGI;
print $q->header();

find (\&wanted, @INC);

sub wanted {
next if (/^\.{1,2}$/);
$list{$_} = $_ if -f && /\.pm$/;
}

my @sorted = sort { lc($a) cmp lc($b) } keys %list;
my $cnt = @sorted;
print "$cnt unique modules found.

";
print "$_
\n" for @sorted;
** this script is provided as-is, no warranty of fitness is expressed or implied. Install and use if you know how, I will not answer questions or provide support for the script.

-Should I always quote my "$variables"?
In general it does no harm to quote your $variables, but its not good Perl programming practice to do so and most of the time is not necessary. When you double-quote your variables you force Perl to make them into strings (stingification), but they already are strings, why do it over again? Numbers do not have to be quoted unless you want them in a string context. Some examples to consider:

$num = "123"; #BAD
$num = 123; #GOOD

somefunction("$num"); #BAD
somefunction($num); #GOOD

$word = 'a string of words';
$copy = "$word"; #BAD
$copy = $word; #GOOD

print "$sentence"; #BAD
print $sentence; #GOOD


also, if you double-quote an array when printing it Perl adds extra spaces, or blanks, between the array elements. This sometimes is handy but sometimes it's not.

@array = `some_command`;
print "@array"; #might not be what you expect
print @array; #printed with no extra blanks

OK, so double-quoting for the most part is not a big deal, but it's better to not quote variables when they shouldn't be quoted. Could save you some typing too.

-What does "Can't Find String Terminator "XXX" Anywhere Before EOF" error mean?
This most often seems to happen when using the print command like this to print some output to the screen:
Code:
print <<"EOF";
Hello, my name is Kevin
EOF
The last line, EOF, which is the end of string terminator, must be flush against the left margin and no spaces or other characters should be to the right of it on the same line.

-How can I output my numbers with commas added?
This subroutine will add commas to your numbers:
Code:
sub commify {
local $_ = shift;
1 while s/^([-+]?\d+)(\d{3})/$1,$2/;
return $_;
}

You call the subroutine where needed in your script, something like:

$num = 16574.33 + 19983745.21;
commify($num);
print $num;

This regex from Benjamin Goldberg will also add commas to numbers:
Code:
s/(^[-+]?\d+?(?=(?>(?:\d{3})+)(?!\d))|\G\d{3}(?=\d))/$1,/g;

** this one is quoted directly from the Perl 5.8.4 Documentation (perlfaq5 - Files and Formats)

I will post more soon.

Geoserv.

PART II

- How can I run/test Perl scripts on my Windows PC?
Besides a Perl interpreter, you also need a web server software installed. If you're running Windows, I can tell you how to install Apache and ActivePerl, to run Perl on your own computer.

First, download the Apache 2 binary distribution from apache.org. When the installer prompts you, set "Network Domain" and "Server Name" to localhost, and "Administrator's Email Address" to your own email addy. Choose the "Typical" setup mode, the default installation folder (C:\Program Files\Apache Group\) is good. When installation is finished, Apache should start automatically as a Windows service. You can check if it's working by going to http://localhost/ (or if you prefer, http://127.0.0.1/) in your web browser. You can now save your files in the /htdocs directory inside the directory you installed Apache in, and access them through http://localhost/filename.

Then, download the ActivePerl package from www.activestate.com. Notice that registering is voluntary. Choose the newest build and Windows / MSI (a Windows installer package). When installing, leave the Custom Setup settings as they are, as well as the installation directory (C:\Perl\). In the next screen, leave "Enable PPM3 to send profile info to ASPN" unchecked. In the next screen, check both "Add Perl to the PATH environment variable" and "Create Perl file extension association". Then the installer will copy all files and generate the HTML documentation - generating the documentation will take a good while so just be patient.

Now you have the Perl interpreter installed, and you can run Perl scripts in it, but to run them through your web browser (as CGI scripts), you still need to configure Apache a little. Go to the Windows start menu -> Programs -> Apache HTTP Server 2.0.xxx -> Configure Apache Server -> Edit the Apache httpd.conf Configuration File, and some code should open up in Notepad. Hit Ctrl+F or choose Edit -> Find (in Notepad), type cgi-script and hit "Find Next". You should come to a line that says #AddHandler cgi-script .cgi. Uncomment it, i.e. remove the pound sign (#) from the beginning of it. Also set it to interpret .pl files as CGI scripts, so you have AddHandler cgi-script .cgi .pl. Then save the file and restart Apache from Start menu -> Programs -> Apache HTTP Server 2.0.xxx -> Control Apache Server -> Restart. You can now save your Perl scripts in the /cgi-bin directory, that is located in the same dir as /htdocs. You run them in your browser through http://localhost/cgi-bin/filename.cgi.

You will also have to use a different shebang line when running Perl scripts on your localhost server. Instead of the typicl web host server shebang line that is similar to this:

#!/usr/bin/perl

you will use:

#!/perl/bin/perl.exe

or

#!C:/perl/bin/perl.exe

or

#!perl

whichever one works for your setup.


If you wish to be able to run Perl scripts from the /htdocs directory too, edit the httpd.conf file again (Start menu -> Programs -> Apache HTTP Server 2.0.xxx -> Configure Apache Server -> Edit the Apache httpd.conf Configuration File), hit Ctrl+F, and search for (the path you see depends on where you installed Apache, that is the default installation directory). Everything below that until a closing (reminds you of HTML doesn't it) are instructions for the /htdocs directory. Inside that block, find a line saying Options Indexes FollowSymLinks, amend it to Options Indexes FollowSymLinks ExecCGI, save the file and restart Apache (Start menu -> Programs -> Apache HTTP Server 2.0.xxx -> Control Apache Server -> Restart). You can now run your CGI scripts in /htdocs too.


At the moment, only .cgi files are ran as CGI scripts, but you may want to run other extensions, such as .pl, .py, .tcl or .rb as CGIs too. Edit the httpd.conf configuration file again, find the line that says AddHandler cgi-script .cgi, change it to AddHandler cgi-script .cgi .pl (you can add as many extensions as you want), then save the file and restart Apache.


There is still one thing you may want to edit; setting Apache to see index.cgi (and index.pl) as directory index files, just like index.html and index.htm are seen. Edit httpd.conf again, and find DirectoryIndex from the file. You should come to a line saying DirectoryIndex index.html index.html.var, amend it to DirectoryIndex index.html index.html.var index.cgi index.pl. You can also add index.htm to it, if you prefer the .htm extension to .html. Then save the file and restart Apache.

- Perl Programming and Memory Usage
Here are some basic tips for keeping memory usage low.

Don't do what is sometimes called "slurping" files:
Code:
open (FILE,"yourfile");
@data = ;
foreach (@data) {
#do something
}
close(FILE);

this reads the entire file into memory. If its just a small file then its not really a big deal.

But this is much better as far as memory consumption is concerned:

Code:
open (FILE,"yourfile");
while () {
#do something
}
close(FILE);

If you have files with thousands and thousands (or more) of lines you probably should be using a while loop.

Use "grep" and "map" only when you really have to as they also slurp files into memory. You can probably use a while loop instead of "grep" or "map" in many situations.

Don't use double-quotes when you don't need to.

- How Do I Check the Length of a String?
To check the length of a string using Perl you use the length() function. Some examples:
Code:
$name = 'Jennifer';

$length = 8;
if (length($name) > $length) {
print "Too long";
}

$num = length($name);
if ($num > 8) {
print "Too long";
}

- How Do I Select a Random Element From an Array?
To select a random element from an array using perl you use the rand function. Some examples:
Code:
@DATA = qw(cat dog fish cow horse pig camel giraffe);

#example 1
$random_element = $DATA[int(rand @DATA)];

#example 2
$index = rand @DATA;
$random_element = @DATA[$index];

if you are using a version of Perl older than 5.004 you must use srand() before trying to select a random element.

Code:
srand():

@DATA = qw(cat dog fish cow horse pig camel giraffe);

#example 1
$random_element = $DATA[int(rand @DATA)];

#example 2
$index = rand @DATA;
$random_element = @DATA[$index];

you can only call srand() once per program.

Perl version 5.004 and higher automatically calls srand() unless srand() has already been called.

- How Can I Determine the NUmber of Elements in an Array?
To determine the number of elements in an array you assign the array to a scalar variable:

Code:
@DATA = qw(cat dog fish cow horse pig camel giraffe);
$number_of_elements = @DATA;
print $number_of_elements;

$number_of_elements will equal 8 for the above example. $DATA[0] through $DATA[7] equals 8 elements.

- [b]

link to trackback page

23 comments:

Anonymous said...

bl qxzy upjc apx bbhy ebhg slc bfhz pw pd cjn lmas emzx tuh pcol krgc qyx ozoy xc
Our updates Recent articles:
http://www.zgyzfxsp.com/bbs/forum.php?mod=viewthread&tid=335280
http://www.alcaldiavillahermosa.com/b2evolution/index.php/bienvenido-a-las-sociales-de#comments
http://www.cruiseshiplawyersblog.com/2012/09/cruise-line-and-cruise-captain-responsible-for-costa-concordia-tragedy.html#comments

Anonymous said...

Very great post. I just stumbled upon your weblog and wished to
mention that I have really loved surfing around your
blog posts. In any case I'll be subscribing to your feed and I'm hoping you write once more very soon!


Check out my weblog :: Jessie Rogers Showers Before Anal Dildo Play With Sara Jaymes And 65533

Anonymous said...

I drop a leave a response whenever I appreciate a post on a site or I
have something to contribute to the discussion.
It's caused by the sincerness communicated in the article I browsed. And after this article "Perl Faq". I was actually excited enough to post a thought ;-) I actually do have a couple of questions for you if you usually do not mind. Is it just me or does it give the impression like some of these remarks look like they are written by brain dead people? :-P And, if you are writing at other online sites, I would like to keep up with everything fresh you have to post. Could you make a list the complete urls of your community sites like your Facebook page, twitter feed, or linkedin profile?

Here is my website; see more

Anonymous said...

Hi there to all, the contents existing at this web site are actually awesome for people knowledge,
well, keep up the good work fellows.

Also visit my web blog - visit website

Anonymous said...

It's very effortless to find out any topic on net as compared to books, as I found this piece of writing at this site.

Here is my blog post :: http://extremefucking.org

Anonymous said...

I rarely write responses, however i did a few searching and wound up here "Perl Faq".
And I actually do have a few questions for you if
you do not mind. Could it be only me or does it seem like some
of these remarks come across like coming from brain dead people?
:-P And, if you are writing on additional places, I'd like to follow everything fresh you have to post. Could you list of the complete urls of your social sites like your twitter feed, Facebook page or linkedin profile?

Also visit my website :: ����

Anonymous said...

I like it when folks get together and share opinions. Great blog, continue the good work!


Feel free to surf to my site :: sweet young brunette - pornharvest.com

Anonymous said...

I know this web page offers quality dependent articles or reviews and
extra information, is there any other web page which offers such stuff in quality?



My web page :: more

Anonymous said...

It's impressive that you are getting thoughts from this paragraph as well as from our dialogue made at this time.

Check out my site ... next page

Anonymous said...

I have learn several excellent stuff here. Definitely value bookmarking for revisiting.

I wonder how so much attempt you set to create such a great informative website.


Take a look at my web page: http://pornharvest.com/index.php?m=2084790

Anonymous said...

If some one needs to be updated with latest technologies
afterward he must be pay a quick visit this site and be up
to date daily.

Here is my homepage good - Pornharvest.com

Anonymous said...

great submit, very informative. I wonder why the other experts of
this sector do not notice this. You must proceed your writing.

I'm confident, you've a great readers' base already!

Feel free to visit my website: like this

Anonymous said...

At this time I am going to do my breakfast, when
having my breakfast coming yet again to read more
news.

Also visit my webpage - a gallery

Anonymous said...

Way cool! Some very valid points! I appreciate you penning this write-up and
the rest of the site is also very good.

my homepage :: see more

Anonymous said...

Thanks very interesting blog!

Here is my web blog http://www.socialswager.com/index.php?do=/profile-26968/info/

Anonymous said...

Hi there it's me, I am also visiting this web page daily, this website is in fact good and the users are actually sharing pleasant thoughts.

Also visit my blog: HTTP://Pornharvest.com/index.php?q=nubiles+jessie_marie&f=a&p=s

Anonymous said...

I am sure this article has touched all the
internet viewers, its really really nice paragraph on building
up new blog.

My homepage; http://pornharvest.com/index.php?m=2339538

Anonymous said...

Generally I do not read article on blogs, however I wish
to say that this write-up very forced me to try and do it!
Your writing style has been amazed me. Thanks, very great article.


Also visit my webpage :: for nubiles alaura lee

Anonymous said...

Every weekend i used to visit this site, as i wish for enjoyment,
since this this web page conations really nice funny information too.


Feel free to surf to my web page - 사용후기 - cheap viagra onlinee

Anonymous said...

Thanks in favor of sharing such a fastidious opinion, paragraph is nice, thats why i
have read it completely

Check out my webpage ... see more

Anonymous said...

Have you ever considered about including a little bit more than just your articles?
I mean, what you say is valuable and everything. Nevertheless think
of if you added some great images or video clips
to give your posts more, "pop"! Your content is excellent but with pics and
video clips, this site could definitely be one of the very best in its field.

Fantastic blog!

Take a look at my blog post read what he said

Anonymous said...

I do not drop many remarks, but after reading through some of the responses here "Perl Faq".
I actually do have some questions for you if you tend not to mind.
Could it be just me or do a few of the responses appear like they are written by brain dead
individuals? :-P And, if you are posting at additional places,
I'd like to follow anything fresh you have to post. Would you make a list of all of your social pages like your linkedin profile, Facebook page or twitter feed?

my webpage http://pornharvest.com/index.php?m=2084127

Anonymous said...

If you would like to obtain a great deal from this article then you
have to apply these methods to your won web site.

Have a look at my homepage: learn more