 |
| |
Perl Statements
NEW!!!
Check my new resource: Perl How To Tutorial eBooks
Perl Statements Menu:
Simple Perl Statements Perl Blocks Perl Compound Statements Perl Control Statements Perl Conditional Statements Perl Loop Statements Perl Loop Controls Perl Jump Statements Perl Modifiers
The statements are one of the most important topics in the Perl language, actually for any programming language. We use statements in order to process or evaluate the expressions. Perl uses the values returned by statements to evaluate or process other statements, and so on. We can point out that a Perl program is a sequence of expressions and statements, from the beginning to the end of the program. Actually, what I said before is not entirely true, a Perl program or script could be more complicated than this, but for the moment the above definition will help you better understand the topics described below. A Perl statement ends with the semicolon character (;) which is used to tell interpreter that the statement was complete. You can put one or more Perl statements on the same line of a Perl script or continue a statement on several lines. Please look at the following example to see some simple Perl statements: 2+4;
$var1 = 2+4; $pi = 3.14;
$var = $var1 +
$pi;
The first statement is a simple addition, the Perl interpreter will execute it but the result of the statement will vanish in the fresh air because it was not assigned to any variable. The next line shows you two statements on the same line. The last two lines show you a statement spread across two lines, the sum of the $var1 and $pi variables will be stored in the $var variable.
Check my new How To Tutorial eBooks (PDF format):to see a lot of fully commented examples that help you use the Perl statements and the Perl buit-in functions in your scripts.
You can group one or more Perl statements in a block. Generally, a block is enclosed by curly brackets {}. Keep in mind that blocks are always bounded by curly brackets, even if your block has only one code line. Within a block we can provide a scope for temporary lexical variables. Every block statement is evaluated by Perl as an individual statement.The syntax format for a Perl BLOCK is as follows: {
statement;
...
statement;
statement
}
Please note that after the last statement of the block you can omit the semicolon, but still it is a good habit to put it (lets say that you change your mind and add some other statement after the last one).See an example of a block used with a foreach statement below: @numbers = (1, 2, 3, 4);
foreach $item(@numbers) {
$item++;
print "$item ";
}
print "\n"; # it prints 2 3 4 5
You can name a block by giving it a label that represents an identifier for it. The label:- precedes the block
- begins with a letter or an underscore (_) and can contain either underscores or alphanumerical characters
- ends with the colon character (:)
As a rule of thumb, I suggest you to use for labels only uppercase characters, so as not to conflict with reserved words - because Perl language is case sensitevily. You use blocks: - with the conditional statements like if and unless
- with the loop statements like while, for, foreach, until
- by itself, and in this case we call them bare or naked blocks
A bare block can be labeled or not and it can be assimilated with a loop that is executed only once and therefore you can use within it the loop controls: next, last, redo. A bare block can be used with one of the following syntax forms:LABEL BLOCK
LABEL BLOCK continue BLOCK
Here continue is a flow control statement and can be used especially in connection with the loop controls. If a bare block is unlabelled, we call it an anonymous block. Please take a look at the following anonymous block sample: {
my $var1 = 2+4; my $pi = 3.14;
my $var = $var1 + $pi;
}
Now, Ill show you an example about how to use the bare block in connection with the continue statement and the loop controls of the Perl statements. Please read carefully the comments on the snippet code, because in the case of a bare block the behavior of these is slightly different.@numbers = (1, 2, 3, 4, 5);
$count = 5;
MYLABEL: {
next if $count-- == 0;
$count1 = $count;
# increment each element of the array
$_++ foreach @numbers;
redo;
} continue
{
print "\@numbers = (@numbers)\n";
}
print "that's all\n";
The output for this code is the following:@numbers = (6 7 8 9 10)
that's all
As you see, every element of the @numbers array was incremented with the value of $count variable. In the case of a bare block, you can use the next control to exit the block (because it is one loop block) and after the exit, Perl will execute the continue block. If you use last instead of next to leave the block, the continue block will be no more executed. The redo control was used to restart the block. In this example we used if and foreach statements with modifiers. To iterate through the elements of the @numbers array, we used the foreach statement with the special variable $_.
Check my new How To Tutorial eBooks (PDF format):to see a lot of fully commented examples that help you use the Perl statements and the Perl buit-in functions in your scripts.
You can group one or more blocks and expressions and you get a compound statement. The next ones are compound statements:if (EXPR) BLOCK else BLOCK
LABEL while (EXPR) BLOCK
LABEL foreach VAR (LIST) BLOCK
where EXPR represents a scalar expression and LIST an expression evaluated in a list context. To define a compound statement we may have more complex examples than the ones mentioned above, by instance with blocks nested in other blocks and so on.The Perl statements are very often used as compound statements. Take a look at the following compound statement example: # a bare block labeled MAIN
MAIN: {
# a while with a block
while($line = <STDIN>){
chomp($line);
# some blocks with if, elsif and else
if($line == 1){
print "You typed 1\n";
} elsif ($line == 2) {
print "You typed 2\n";
} else {
print "You typed $line, must type 1 or 2\n";
}
}
}
A possible output for this code:1
You typed 1
2
You typed 2
3
You typed 3, must type 1 or 2
^Z
C, C++, Java programmers please note that the looping and control statements require curly braces around blocks of code even if you have only one line of code, as you can see in the if statement used above.
The control statements are an important category of the Perl statements. Im going to show you a brief panorama of the Perl control statements their main purpose being that to change the sequential flow of a Perl program. We can divide the control statements in two main categories: conditional statements - which use an expression to check if a condition is met and loop statements - which checks a condition and executes the statements included in curly braces until that condition is evaluated true/false.Inside a loop statement you can use the loop controls to alter the behavior of a Perl loop. Being a structured programming language, Perl has just an entry point for any block but it allows more ways to exit the block like in the case you want to finish earlier the loop iterations. You can also use the goto jump statement to modify the flow of the program and jump directly at any label in the program. Anyway, be cautious if you want to use it, especially if you want to jump inside a block or a subroutine code. Perl allows you to write a conditional or loop statement on a single code line, by using modifiers. The statement modifier will be placed at the end of the statement you want to modify.
Check my new How To Tutorial eBooks (PDF format):to see a lot of fully commented examples that help you use the Perl statements and the Perl buit-in functions in your scripts.
The expressions in a conditional statement are evaluated in a boolean context. The conditional statement if with its elsif and else clauses is more often used, but you can use the unless and switch Perl statements, too:- if which will execute a block only when a conditional expression is evaluated as true; if the expression is true, the block between the curly braces will be executed
- unless which will execute the block when a condition expression is evaluated as false it is the reverse of the if statement, i.e. like an if test with the opposite condition
- switch well, Perl 5 until 5.10 version has no switch statement to implement a case mechanism in order to avoid the if-elsif-else pattern, but it is easy to build one. Perl 5.9 and 6 come with a built-in switch but it will be spelled "given"
If you need to execute a code block more than once, process known as iteration, you must use this type of Perl statements. A loop statement generally has an optional label and allows you execute the Perl statements enclosed by curly braces repeatedly, until the expression condition is evaluated as true/false. All the basic Perl loop statements imply the execution of three steps:- evaluate an expression condition in a boolean context
- if the expression is evaluated as true/false, Perl will execute the next block of statements
- resume the code with the step 1
There are slightly differences between the basic Perl loop statements, and you can choose the one which is most appropriate for your task:- while executes the block repeatedly as long as a conditional expression is true; the expression is tested before the first iteration of the loop
- do-while you can use this loop statement when you need to execute a piece of code at least once and then iterate consecutively while the condition is true
- until is like while, except that it executes the block only if the expression is false; the expression will be tested before the first iteration, too
- do-until operates similar to do-while, except that it will iterate only if the conditional expression is evaluated false
- for executes a given set of statements for a certain number of times; in the case of the for statement, the conditional expression consists of three parts (initialization, condition, increment), delimitated by a semicolon symbol
- foreach operates over a list of values or array by setting consecutively a control variable to each element of the list; some more "perlish" programmers use the word "for" instead of "foreach" because Perl interpreter will easily distinguish between an original for statement (which contains semicolons) and a "for(each)" statement
If you need more looping constructs than the basic loop statements provided by Perl, you can build your own.
Check my new How To Tutorial eBooks (PDF format):to see a lot of fully commented examples that help you use the Perl statements and the Perl buit-in functions in your scripts.
In order to override the loop normal behavior, Perl language provides three loop control operators:- next is used inside a looping block to skip the following statements of the block when a condition is met, it terminates the current iteration of the loop and then continues with the next iteration, until the end of the loop is reached it is similar with the continue statement from C language
- last is like the next control except that it will immediately end the execution of the loop it is similar with the "break" statement from C language
- redo returns to the top of the current iteration of the block, without testing any condition
You can change the behavior of your code sequence by using jump statements. For this, Perl provides you the goto statement which let you jump to a label in your program or to call to a certain subroutine from the currently running subroutine; goto is one of the most rarely used Perl statements.
Sometimes its necessary, especially for readability, to use a more compact notation. To help with this, Perl allows the use of statement modifiers. To be more explicit, the statement modifiers are placed at the end of the Perl statements that are modified. So you can follow any simple statement with a single modifier: if, unless, while, until, foreach, as in the following syntax forms:statement if EXPR
statement unless EXPR
statement while EXPR
statement until EXPR
statement foreach EXPR
where EXPR represents a condition that it will be evaluated first.Please have a look at the following snippet code in order to highlight the topics: $isPerl = 1;
$a = "Perl Statements\n" if $isPerl == 1;
# it assigns to $a the string value "Perl Statements"
# if the value of $isPerl variable is equal with 1
print $a;
# it prints "Perl Statements"
$c = 2;
$b = 1 unless $c != 2;
# it assigns 1 to $b if $c equals 2
print "b = $b\n";
# it prints b = 1
$count = 1;
$count++ while $count < 6;
# it increments $count 5 times
print "Count = $count\n"; #it prints Count = 6
$count-- until $count == 1;
# it decrements $count 5 times
print "Count = $count\n"; #it prints Count = 1
@numbers = (1, 2, 3, 4, 5);
$_+=5 foreach @numbers;
# increments each element of the array with 5
print "@numbers\n";
# it prints 6 7 8 9 10
Subscribe now to my FREE newsletter (regarding tips and tricks to manipulate multidimensional arrays and hashes in Perl) and you'll receive a link to download for FREE my Perl chomp Function Tutorial eBook (a $7.50 value), it's a bonus for you and I hope you'll enjoy it. You can see its Table of Contents here (if you subscribe to my free newsletter, you don't have to pay for this eBook or use your paypal account).
Don't forget to check my new How To Tutorial eBooks (PDF format):to see a lot of fully commented examples that help you use the Perl statements and the Perl buit-in functions in your scripts.
NEW!!!
Do you want more information about the basic Perl topics?
Check my new "Perl How To" Tutorial eBooks page where I'll answer the most frequent questions regarding some topics :
Perl How To Tutorial eBooks
Table of Contents:
A Perl Script Install Perl Running Perl Perl Data Types Perl Variables Perl Operators Perl Lists Perl Arrays Array Size Array Length Perl Hashes Perl Statements Perl if Perl unless Perl switch Perl while Perl do-while Perl until Perl do-until Perl for Perl foreach Built-in Perl Functions Functions by Category String Functions Array Functions Functions in alphabetical order chomp chop chr crypt defined grep hex index join lc lcfirst length map oct ord pack pop push qw reverse rindex scalar shift sort splice split substr uc undef unshift
return to Perl Basics
Would you like to create your own website like this one? Hit the Alarm Clock!


|
|