|
Volume 2 Issue 11, November 2003 Perl |
Copyright (C) 2003 by Steve Litt. All rights reserved. Materials from guest authors copyrighted by them and licensed for perpetual use to Linux Productivity Magazine. All rights reserved to the copyright holder, except for items specifically marked otherwise (certain free software source code, GNU/GPL, etc.). All material herein provided "As-Is". User assumes all risk and responsibility for any outcome.
|
and Rapid Learning: Secret Weapon of the Successful Technologist by Steve Litt |
[ Troubleshooters.Com
| Back Issues |Troubleshooting Professional Magazine
]
|
|
CONTENTS
| News Mag |
Submission URL or Email address |
Comments |
| Slashdot |
http://slashdot.org/submit.pl |
Just fill in the short form. |
| LinuxToday |
http://linuxtoday.com/contribute.php3 |
Just fill in the short form. |
| Linux Weekly News |
lwn@lwn.net |
Just tell them the URL, why you like it. |
| NewsForge |
webmaster@linux.com |
Just tell them the URL, why you like it. |
| VarLinux |
http://www.varlinux.org/vlox/html/modules/news/submit.php |
Just fill in the short form. |
| LinuxInsider.Com, Newsfactor Network |
http://www.newsfactor.com/perl/contact_form.pl?to=contact |
Just tell them the URL, why you like it. |
| The Linux Knowledge Portal |
webmaster@linux-knowledge-portal.org |
Just tell them the URL, why you like it. |
| OS News |
http://www.osnews.com/submit.php |
Just tell them the URL, why you like it. |
| DesktopLinux |
http://www.desktoplinux.com/cgi-bin/news_post.cgi |
Only for LPM issues involving the Linux desktop, not
for programming or server issues. |
| Language |
Description |
Advantages |
Disadvantages |
Availability |
| C |
A slim, trim, machine level compiler. |
|
|
Installed by default on all UNIX/Linux/BSD machines. Can be purchased for Windows. |
| C++ |
C + OOP |
|
|
Available for most UNIX/Linux/BSD machines, and installed by default on Linux machines. Can be purchased for Windows. |
| Java |
A machine independent language compiling to language
specific bytecodes. Built from the ground up to be object oriented. |
|
|
Available on all major platforms. |
| Python |
A widely ported interpreter well integrated with OOP. |
|
|
Available on UNIX, Linux, BSD and Windows. Packaged
with most Linux distributions, but often not installed. |
| Ruby |
An interpreter built from the bottom up with OOP in
mind. Somewhat similar to Perl and Python. |
|
|
Available, but seldom installed, on Linux. On other
platforms one can compile Ruby from scratch and install. |
| TCL |
An interpreter whose syntax and use is very different
from C or the other languages discussed here. Those who know how can write
substantial programs with just a few lines of TCL, but it's not very scalable. |
|
|
Bundled with, and usually installed on Linux. Available
for other platforms, including Windows. |
| QT |
A compiled language designed to create graphical applications. |
|
|
Bundled with Linux, available via compilation on most
other platforms. |
| gTk |
A compiled language designed to create graphical applications. |
|
|
Bundled with Linux, available via compilation on most other platforms. |
| bash | A command interpreter that can be used as a language. |
|
|
Installed on all Linux boxes. Bash, or something very
similar, is installed on almost all UNIX and BSD boxes. Can only be achieved
on Windows with mating products such as |
| Perl NOTE: This evaluation is for Perl 5. |
An interpreter optimized to do big things with few
lines. OOP has been tacked on after the fact. |
|
|
Installed by default on all Linux, BSD and Unix machines.
Available for Windows and all other platforms. |
my @output = `./child.pl`; |
my $string = '$tax = (isFood($product) | isMedicine($product) ? 0.06 * price : 0);';And anywhere in the program you could use it like this:
my $tax;In the preceding, you'd also need to define functions isFood($)and $isMedicine($). This way, you could change the tax formula by changing the data. If the government started taxing medicine, you could eliminate the$isMedicine()from the string. If the tax rate went up to 7%, you could change the 0.06to 0.07.
my $product = 19;
my $price = 1.00;
eval $string;
print "Price for product $product is $price, tax is $tax.\n";
print "Hello World\n"; |
perl ./test.plThe file will run and produce the following output:
[slitt@mydesk slitt]$ perl ./test.pl |
#!/usr/bin/perl -w |
chmod a+x ./test.plFinally, run the program with the following command:
./test.plThe program's output is identical -- all you've done is eliminated the need for manually invoking perl on the command line.
#!/usr/bin/perl -w |
#!/usr/bin/perl -w |
#!/usr/bin/perl -w |
[slitt@mydesk slitt]$ ./test.pl |
| Operator |
Functionality |
Example |
$var contains |
| = |
Assignment |
$var = 8; |
8 |
| + |
Addition |
$var = 8 + 3; |
11 |
| - |
Subtraction |
$var = 8 - 3; |
5 |
| * |
Multiplication |
$var = 8 * 3; |
24 |
| / |
Fractional Division (5/2 is 2.50, not 2) |
$var = 8 / 3; |
2.66666666666667 |
| % |
Modulus |
$var = 8 % 3 |
2 |
| Whole number division |
$var = (8-(8%3))/3 |
2 |
| Operator |
Functionality |
Example |
| > |
Numeric greater than |
if($var > 8) |
| >= |
Numeric greater than or equal |
if($var >= 8) |
| < |
Numeric less than |
if($var < 8) |
| <= |
Numeric less than or equal | if($var <= 8) |
| == |
Numeric equality |
if($var == 8) |
$var = "George" . " " . "W." . " " . "Bush";In the preceding, $var now contains "George W. Bush".
substr EXPR,OFFSET,LENGTH,REPLACEMENTLENGTH and REPLACEMENT are optional. Personally, I seldom use REPLACEMENT because it's clearer to replace text with a concatenation after truncation. Here are some ways you can use substr() to truncate from the right and from the left of a string. In the following examples, imagine that:
$string = "Perl Developer":
| Task |
Statement |
Value of $var |
| Remove 3 characters from the front of the string |
$var = substr($string, 3); |
"l Programmer" |
| Remove all but the 3 final characters from the string |
$var = substr($string", -3); | "mer" |
| Remove the 3 final characters from the string | $var = substr($string, 0, - 3); |
"Perl Program" |
| Remove all but the first 3 chaaracters from the string |
$var = substr($string, 0, 3); |
"Per" |
| Operator |
Functionality |
Example |
| gt |
String greater than |
if($var gt "cccc") |
| ge |
String greater than or equal |
if($var ge "cccc") |
| lt |
String less than |
if($var lt "cccc") |
| le |
String less than or equal | if($var le "cccc") |
| eq |
String equality |
if($var eq "cccc") |
#!/usr/bin/perl -w |
#!/usr/bin/perl -w |
#!/usr/bin/perl -w |
#!/usr/bin/perl -w |
[slitt@mydesk slitt]$ ./test.pl |
#!/usr/bin/perl -w |
[slitt@mydesk slitt]$ ./test.pl |
unless($number > 1000)Another branching method is short circuit logic. For instance:
{
print "Number less than 1000\n";
}
writeLogFile() || writeErrorFile() || die "cannot write files";The preceding calls writeLogFile(). If that returns non-zero, nothing to the right of it is called. But if it returns 0, then writeErrorFile()is called. If that returns non zero, nothing to the right is called. However, if it returns zero, then the program dies with the message "cannot write files". When used right this can be a readable and compact way of programming.
last if x == 0;The preceding are if and unless statements respectively, but they're written with the action first and the test second. The main advantage is that parentheses and braces are not required, making this a much more readable form for if and unless statements with a single line of code for the action. Do not use these constructs if there are several statements to be executed, as it would be terribly confusing to someone reading your code.
print "Not interested\n" unless $price < 1500;
#!/usr/bin/perl -w |
[slitt@mydesk slitt]$ ./test.pl |
| @books |
An array variable (list variable) |
| $books[3] |
The fourth element of the @books array |
| $books |
A scalar not related to @books |
my @books;You can declare and initialize an array like this:
my @books = ("Cujo", "Carrie", "Christine");
Look carefully at the preceding. Contrary to every instinct of an experienced
computer programmer, the elements are inside parentheses, not square brackets.
As if that's not confusing enough, when directly initializing a reference
to an array, square brackets are used for that purpose. References are discussed
later in this article.
#!/usr/bin/perl -w |
#!/usr/bin/perl -w |
|
NOTE
Do not confuse length() with $#arrayname. The former returns the length of a string, and is meaningless when applied to an array. The latter returns the subscript of the last element of an array, and is meaningless when applied to a string. Unlike C strings, Perl strings are not an array of characters, so there's no relationship between arrays and strings. There are, however, functions to convert between strings and arrays. |
#!/usr/bin/perl -w |
[slitt@mydesk slitt]$ ./test.pl |
#!/usr/bin/perl -w |
[slitt@mydesk slitt]$ ./test.pl |
#!/usr/bin/perl -w |
[slitt@mydesk slitt]$ ./test.pl |
| Function |
Action graphic |
Description |
||||||||||||
| push @DESTARRAY, @SRCARRAY |
|
Places the elements of the @SRCARRAY at
@DESTARRAY's end ( starting immediately after the current
final used subscript) |
||||||||||||
| pop @ARRAY |
|
Returns and removes the array's highest subscripted
element. |
||||||||||||
| shift @ARRAY |
|
Returns and removes the array's element 0, and then
shifts all other elements down one. |
||||||||||||
| unshift @DESTARRAY, @SRCARRAY |
|
Shifts all elements in @DESTARRAY up (higher
subscript) by the number of elements in @SRCARRAY, and then copies
the elements of @SRCARRAY to the (now) unused lower elements of
@DESTARRAY. |
#!/usr/bin/perl -w |
#!/usr/bin/perl -w |
#!/usr/bin/perl -w |
#!/usr/bin/perl -w |
[slitt@mydesk slitt]$ ./test.pl |
#!/usr/bin/perl -w |
[slitt@mydesk slitt]$ ./test.pl |
my @keys = sort keys %person;To sort it in reverse order, use the reverse() function or
my @keys = reverse sort keys %person;Another way to get the reverse sort is with the block syntax of sort():
my @keys = sort {$b cmp $a} keys %person;
Speaking of the block syntax of sort, it's a necessity if you want to sort
by values instead of keys:my @keys = sort {$person{$a} cmp $person{$b}} keys %person;
In the preceding line, $a represents element ss in the array, while
$b represents element ss+1. Everything in the block is considered
the sort's comparison subroutine, be called back for each pair of array elements.
In this case, instead of comparing the elements, we compare the hash values
associated with the elements. Pretty cool, huh?
#!/usr/bin/perl -w |
[slitt@mydesk slitt]$ ./test.pl |
if(exists($hashname{$keystring}) {do_something();}
To see whether an existing (or nonexistent) key's value is defined, use this:if(defined($hashname{$keystring}) {do_something();}
| Variable | Instantiating the variable |
Instantiating a reference to it |
Referencing it | Dereferencing it | Accessing an element |
| $scalar | $scalar = "steve"; |
$ref = \"steve"; |
$ref = \$scalar | $$ref or ${$ref} |
N/A |
| @list | @list = ("steve", "fred"); |
$ref = ["steve", "fred"]; |
$ref = \@list | @{$ref} | ${$ref}[3] $ref->[3] |
| %hash | %hash = ("name" => "steve", "job" => "Troubleshooter"); |
$hash = {"name" => "steve", "job" => "Troubleshooter"}; |
$ref = \%hash | %{$ref} | ${$ref}{"president"} $ref->{"president"} |
| FILE | $ref = \*FILE | {$ref} or scalar <$ref> |
#!/usr/bin/perl -w |
sub printHello() |
sub biggest($$) |
sub biggest($$) |
my $wwii = 1941; |
| Calling the subroutine | Constructing the subroutine |
%globals; # now print globals |
sub printGlobals |
#!/usr/bin/perl -w |

