Condition and Looping Construct
Perl has most of the usual looping and conditional construct expect the case and switch but it is also available in perl modules (CPAN).
if
if ( condition ) {
…
} elsif ( other condition ) {
…
} else {
…
}
unless
unless ( condition ) {
…
}
while
while
while ( condition ) {
…
}
for loop
for ($i = 0; $i <= $max; $i++) {
…
}
The C style for loop is rarely needed in Perl since Perl provides the more friendly list scanning foreach loop.
foreach
foreach (@array) {
print “This element is $_\n”;
}
Input in Perl
<STDIN> is used for input. eg.
print “/n Enter your 1st name:”
my $name = <STDIN>;
Chomp Operator
This operator is used to remove the \n from the input and if the string ends in a newline character, chomp can get rid of the newline.
* $text = “a line of text\n”; # Or the same thing from <STDIN>
* chomp($text); # Gets rid of the newline character
Basic program to show the demo:
#!/usr/bin/perl -w # program to show the use of chomp operator. Take three text from user and print them as text1 | text2 | text3. use strict; my $var1; print "Enter 1st text:"; $var1 = <STDIN>; chomp ($var1); print "Enter 2nd text:"; $var2 = <STDIN>; chomp ($var2); print "Enter 3rd text:"; $var3 = <STDIN>; chomp ($var3); print "The resulting text:\n"; print "$var1|$var2|$var3\n";
”’The undef value”’
What happen when you try to use the scalar value when its value is not initialized. It uses the undef. Its neither a string nor a number but a separate kind of the scalar value. As its value is equal to zero in case if used with number and empty string if used with string, so frequently used as string and number accumulator.
$string .= “more text\n”; Acts as string accumulator.
$sum += 5; Number Accumulator