HomeHome  PortalPortal  FAQFAQ  SearchSearch  RegisterRegister  Log in  
openFate
openFATE - openSUSE feature tracking
Similar topics
Latest topics
» Difference between 42.2 and 42.1
by findoctr Thu Dec 15, 2016 7:53 pm

» openSUSE Leap 42.1 ?
by findoctr Fri Feb 05, 2016 8:09 pm

» Happy Turkey Day
by findoctr Thu Nov 26, 2015 1:45 pm

» Happy 4th of July!
by bozo Sat Jul 04, 2015 12:56 pm

» It's been a while ...
by bozo Mon Feb 23, 2015 8:34 pm

» Mondo chillers
by bozo Wed Feb 18, 2015 5:11 am

Navigation
 Portal
 Index
 Memberlist
 Profile
 FAQ
 Search
IRC Channel
You can also find us on IRC's freenode.net as #suseunbound.

Share | 
 

 Perl basics

View previous topic View next topic Go down 
AuthorMessage
welan
Admin
avatar

Posts : 248
Join date : 2010-02-23
Age : 54
Location : snow drift in minnesota

PostSubject: Perl basics   Thu Feb 25, 2010 8:20 pm

To create a Perl script, use a text editor
to enter Perl commands, save the file with a .pl extension (such as sample.pl), and then use chmod to mark the file as executable. The extension is not required, but it's a common Unix convention and will help you identify your Perl source files without looking inside.
Here's a very simple Perl script:
#!/usr/bin/perl
print "I am here. \n";
The mysterious first line starting with "pound splat slash" is required for all Perl scripts to run; it tells the system where to find the Perl interpreter. Hopefully, you've already figured out that this program prints a message followed by the newline character.
Unlike the echo command in Bash scripts, Perl's print command doesn't automatically send a carriage return and line feed. If you forget the \n sequence, the next print command will start on the same line. Also note that all Perl statements must end with a semicolon.
A variable in a Perl script is a means of referencing a numeric or character value. As in Bash scripts, Perl doesn't require you to declare a type for your variables. Perl figures out by context whether the value should be treated as a number or a character string and will even perform character-to-numeric value conversions when necessary.
To assign or access the value (contents) of a variable, prefix it with a dollar sign. Spaces before or after the equal sign are optional, but if you want to assign a variable that contains character data, you must put quotation marks around the string.
$num=5;
$stuff = "chocolate truffles";
$user = $ENV{USER};
In these examples, Perl assigns 5 to the numeric variable $num, "chocolate truffles" to the variable $stuff, and the value of the USER environment variable to $user.
This is a good time to note that there are several distinct ways to use quotation marks in a Perl script. Let's look at the differences among single quotation marks, double quotation marks, backticks, and the backslash character and then follow up with some examples.
· Single quotation marks, as in the preceding example, will always get you exactly what's inside the quotation marks--any characters that might otherwise have special meaning (like the dollar sign or the backslash) are treated literally.
· Use double quotation marks when you want to assign a string that contains special characters that need to be interpreted.
· The backslash is used to escape (treat literally) a single character (such as $ or *) that might otherwise be treated as a special character.
· Use backticks to indicate that the string is a Linux command that should be executed, with the results assigned to a variable.
Now let's look at some examples that show when to use each method of quoting:
$user = $ENV{USER};
print 'Good Morning $user';
Yields: Good Morning $user

$user = $ENV{USER};
print "Good Morning $user";
Yields: Good Morning hermie
In the first case, the results would probably not be what you wanted. The single quotation marks caused Perl to not treat $user as a variable. In the second case, the results look much better. The double quotation marks allowed Perl to substitute the value of $user in the string.
Here's another example that demonstrates a common error:
$costmsg = "Price is $5.00";
print "$costmsg";
Yields: Price is .00
We thought enough to quote the string, but the dollar sign tells Perl to use the value in the $5 variable, which is as yet undefined. We can easily solve the problem by prefixing the dollar sign with a backslash, as shown here:
$costmsg = "Price is \$5.00";
print "$costmsg";
Actual result: Price is $5.00
Finally, here's an example using backticks to execute a Linux command and capture the results in a Perl variable:
$currdir = 'pwd'
print "Current directory is $pwd";
Yields: Current directory is /home/hermie
Arguments are the values you pass to a Perl script
. Each value on the command line after the name of the script will be assigned to the special variables $ARGV[0], $ARGV[1], $ARGV[2], and so on. The number of arguments passed to the script is stored in the $#ARGV variable, and the full argument string is in the variable @ARGV. The name of the currently running program is stored in the $0 variable
Let's try some examples working with arguments and other special variables. Create an executable script called testvars.pl containing these lines:
#!/usr/bin/perl
print "My name is $0 \n";
print "First arg is: $ARGV[0] \n";
print "Second arg is: $ARGV[1] \n";
print "Third arg is: $ARGV[2] \n";
$num = $#ARGV + 1; print "How many args? $num \n";
print "The full argument string was: @ARGV \n";
Now if you run this script, here's what you'll see:
$ ./testvars dogs can whistle
My name is testvars.pl
First arg is: dogs
Second arg is: can
Third arg is: whistle
How many args? 3
The full argument string was: dogs can whistle
Just a few notes about that example. I did say that the $#ARGV variable contained the number of arguments, but I lied--sort of. Since the arguments are numbered starting at zero, you have to add one to the value of $#ARGV to get the actual number of arguments. It's a bit weird, but if you're a fan of the C language, it'll all seem quite normal.
Also note that the @ARGV variable doesn't start with a dollar sign. That's because it's an array variable, as opposed to the regular scalar variables we've worked with so far. An array can be thought of as a list of values, where each value is addressed by a scalar (dollar sign) variable and an index number in square brackets, as in $ARGV[0], $ARGV[1], and so on. Don't worry too much about arrays for now--that's a topic for more study on your own.
A Perl script
that's just a sequence of commands executed one after the other isn't very exciting. Let's look at how to use if/then/else logic and looping constructs to control the flow of a Perl
program.
Conditional Operations The general form of an if-then-else construct is shown here, with the actual syntax shown in boldface and the parts you must supply in normal type:
if ( condition is true ) {
execute these commands
}
else {
execute those commands
}
The else clause is optional, but you can also have nested if clauses by using the elsif construct like this:
if ( condition is true ) { execute these commands }
elsif { execute those commands }
elsif { execute those commands }
else { execute those commands }
So what kind of conditions can we test for? For number and string comparisons, here are the conditional expressions you can use. In other words, any of these expressions can go inside the parentheses of the if or elsif statement:
Numbers Strings Result
$a == $b $a eq $b True if $a is equal to $b.
$a != $b $a ne $b True if $a is not equal to $b.
$a > $b $a gt $b True if $a is greater than $b.
$a < $b $a lt $b True if $a is greater than $b.
$a >= $b $a ge $b True if $a is greater than or equal to $b.
$a <= $b $a le $b True if $a is less than or equal to $b.
Using the wrong comparison operator is a common Perl coding error, and is frustrating to debug. For example, if you use the == operator to compare two strings, you will not get the expected result.
You can also test certain file conditions, such as whether or not files exist, the type of file, and so on. Here are the conditional expressions for files:
Conditional Expression Result
-e $somefile True if somefile exists.
-f $somefile True if somefile exists and is a plain file.
-d $somefile True if somefile exists and is a directory.
-s $somefile True if somefile contains data (the size is not zero).
-r $somefile True if somefile is readable.
-w $somefile True if somefile is writable.
-x $somefile True if somefile is executable.
And finally, here are the logical operators, for performing tests that involve and, or, and not conditions:
Operator Result
$a && $b True if both $a< EM> and $b are true.
$a and $b Same as above.< /P>
$a || $b True if either $a or $bi s true.
$a or $b Same as above.< /P>
! $a True if $a is false.
not $a Same as above.
Some if/then/else Examples
Here are some examples using the conditional expressions just listed. Note that the spaces on either side of the parentheses and braces are optional, and the placement of them is largely a matter of style.
if ( $carprice > 20000 )
{ print 'Too rich for my blood.'; }
else
{ print 'Can you get that model in blue?'; }

if ( $maker eq "Buick" )
{ print 'Have you driven a Ford lately?'; }

if ( -r $myfile && -s $myfile )
{
print "The $myfile file is readable and contains data."
}
The case Statement
Most languages provide a case or switch statement that lets you compare a string with several possible values and execute a block of code when a match is found. Perl does not, but it does provide a way to implement this procedure. Here's an example of the SWITCH construct, with the syntax shown in boldface and the parts you would supply in normal type:
SWITCH: {
if ( $A eq "ls" ) { system("ls"); last SWITCH };
if ( $A eq "pwd" ) { system("pwd"); last SWITCH };
if ( $A eq "date" ) { system("date"); last SWITCH };
print "None of the args were very interesting. \n";
}
In this example, if the value of $A was ls, the first block of commands would execute. If the value of $A was pwd, the second block of commands would execute. Otherwise, the rest of the commands in the SWITCH clause would execute. The last SWITCH command tells Perl to short-circuit the rest of the stuff in the SWITCH clause, so as soon as one of the conditions is satisfied, the others are ignored.
Shell scripts
written in Bash can implement looping, or iteration, with the while, until, and for constructs. In each case, a block of code is executed repeatedly until a loop exit condition is satisfied. The script then continues on from that point.
The while Statement In a while loop, the block of code between the { and } braces is executed so long as the conditional expression is true. Think of it as saying, "Execute while this condition remains true." Here's an example:
while (@ARGV) {
print "ARG: $ARGV[0] \n";
shift @ARGV;
}
This trivial example prints the value of each argument passed to the shell script. Translated to English, the while condition says to continue so long as the input argument string is not null. You might think that this loop would continue to print the first argument $ARGV[0] forever and ever, since you don't expect the value of the @ARGV variable (the list of arguments from the command line) to change during the course of running the script. You'd be right, except that I slipped the shift command into the body of the loop.
What shift does is discard the first argument and reassign all the $ARG variables--so the new $ARGV[0] gets the value that used to be in $ARGV[1] and so on. Accordingly, the value in @ARGV gets shorter and shorter each time through the loop, and when it finally becomes null, the loop is done.
The until Statement
The until construct works almost exactly the same as while. The only difference is that until executes the body of the loop so long as the conditional expression is false, whereas while executes the body of the loop so long as the conditional expression is true. Think of it as saying, "Execute until this condition becomes true."
Let's code the previous example using an until loop this time and making it a little fancier by adding a counter variable:
$count=1;
until ( ! @ARGV ) {
print "Argument number $count : $ARGV[0] \n";
shift;
$count++;
}
The only new concept here is the strange-looking line that increments the counter. The $count++ syntax is equivalent to $count=$count+1, but the former is more common in Perl and C language programming. You can also decrement a value using the $count-- syntax.
The foreach Statement
The foreach statement provides yet another way to implement a loop in a Perl script. The general form of the for construct is shown here:
foreach $item ( in-some-array ) {
do something with $item
}
Each time through the loop, the value of the $item variable is assigned to the next item in the array. When you've processed all the items in the array, the loop is done. Here's an example similar to the until and while loops you saw earlier in this section:
foreach $var (@ARGV)
{
print "NEXT ARG: $var \n";
}
One common operation
in Perl is to open a text file and process it line by line. You might be creating a report or just sifting through the file to find certain strings. This example opens a file whose name is stored the $file variable and then prints each line that starts with the pound sign:
open MYFILE, $file or die "Can't open $file: $! \n";
while (<MYFILE>) {
if (/^#/) { print "MATCH: $_"; }
}
A few things may need explaining here. The open command assigns a file handle (in this case, MYFILE) to the file named in the $file variable. You can use any file handle or variable names you like in the open command. If the file cannot be opened for some reason (it doesn't exist, it isn't readable, and so on), then the program will terminate (courtesy of the die command) with a message like this:
Can't open panda.txt: No such file or directory
The special variable $! contains the reason for the failure and was substituted into the error message. If the file is opened successfully, the program continues, and the <MYFILE> construct will return the next line from the file in the $_ variable. (You'll find that a lot of Perl functions use this special $_ variable.) When the end of the file is reached, <MYFILE> will return a null value, causing the loop to terminate.
One mystery remains: What's this (/^#/) stuff all about? Remember the grep command, and the discussion of regular expressions? If you think about it, the little Perl program in the previous example acts a lot like grep, since it sifts through each line and prints it if a pattern is matched.
In Perl, the forward slashes indicate that a pattern match is to be performed. The regular expression inside the slashes defines the search pattern, and $_ is the variable that the search is performed on. In our case, the ^# inside the slashes means to match only lines that begin with the pound sign. So if we make the previous example a bit more generic, allowing it to get the search pattern and file name from the command line, it will behave almost exactly like the grep utility:
open MYFILE, $ARGV[1] or die "Can't open $ARGV[1]: $! \n";
while (<MYFILE>) {
if (/$ARGV[0]/) { print "MATCH: $_"; }
}
Learn More about Perl
We've barely scratched the surface of what you can do with the Perl language. Try the man perl command to get more information on Perl, read Programming Perl by Larry Wall (O'Reilly & Associates), the inventor of the Perl language, or visit the Perl Institute Web site
at http://www.perl.org.


As always thank you for flying Penguin Air

_________________
An expert is a man who tells you a simple thing in a confused way in such a fashion as to make you think the confusion is your own fault. 
Back to top Go down
 
Perl basics
View previous topic View next topic Back to top 
Page 1 of 1
 Similar topics
-
» Selenium IDE Get Table Row Count --Perl
» Avoid browser closing on selenium RC shutdown
» Loading a config file selenium (PERL)
» Not able to click on "OK" in Alert box

Permissions in this forum:You cannot reply to topics in this forum
SUSEUnbound :: Extended Documents and How-tos :: Extended Documents-
Jump to: