<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>UseStrict Consulting &#187; Control Structures</title>
	<atom:link href="http://usestrict.net/tag/control-structures/feed/" rel="self" type="application/rss+xml" />
	<link>http://usestrict.net</link>
	<description>Professional IT Solutions &#38; Training</description>
	<lastBuildDate>Sat, 12 May 2012 14:25:42 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Perl Crash Course: Control Structures</title>
		<link>http://usestrict.net/2009/04/perl-crash-course-control-structures/</link>
		<comments>http://usestrict.net/2009/04/perl-crash-course-control-structures/#comments</comments>
		<pubDate>Wed, 15 Apr 2009 03:06:22 +0000</pubDate>
		<dc:creator>vinny</dc:creator>
				<category><![CDATA[Perl]]></category>
		<category><![CDATA[Control Structures]]></category>
		<category><![CDATA[Perl Course Howto]]></category>

		<guid isPermaLink="false">http://usestrict.net/?p=409</guid>
		<description><![CDATA[Basics on Perl control structures]]></description>
			<content:encoded><![CDATA[<p><strong>by André Batosti<br />
revision: Fernando Giorgetti and Vinny Alves</strong></p>
<p>Control Structures are used to control the flow of a program. We are going to see programs that can iterate (loop) or make decisions (conditionals) based on the state of variables.</p>
<p>More interesting possibilities arise when we introduce control structures and looping. Perl supports lots of different kinds of control structures which tend to be like those in C, but are very similar to Pascal, too.<br />
<span id="more-409"></span><br />
<code><br />
</code></p>
<h3>Conditionals</h3>
<p>The simplest control structures are the <tt>if</tt> and <tt>unless</tt> statements. Its syntax basically follows the rule below:</p>
<pre name="code" class="php">
if ( expression ) {
    instruction1;
    instruction2;
}
</pre>
<p>Value obtained from &#8220;expression&#8221;, determines whether it will be considered as <tt>true</tt> or <tt>false</tt>. Table below helps you to identify the meaning of values based on how Perl interprets expressions.</p>
<table border="1" cellpadding="0">
<tbody>
<tr>
<td><strong>Expression</strong></td>
<td><strong>String/Number?</strong></td>
<td><strong>Boolean value</strong></td>
</tr>
<tr>
<td>0</td>
<td>number</td>
<td>false</td>
</tr>
<tr>
<td>0.0</td>
<td>number</td>
<td>false</td>
</tr>
<tr>
<td>0.0000</td>
<td>number</td>
<td>false</td>
</tr>
<tr>
<td>&#8220;&#8221; or &#8221;</td>
<td>string</td>
<td>false</td>
</tr>
<tr>
<td>&#8220;0&#8243;</td>
<td>string</td>
<td>false</td>
</tr>
<tr>
<td>&#8220;0.0&#8243;</td>
<td>string</td>
<td><strong>true</strong></td>
</tr>
<tr>
<td>undef</td>
<td>N/A</td>
<td>false</td>
</tr>
<tr>
<td>42 &#8211; (6 * 7)</td>
<td>number</td>
<td>false</td>
</tr>
<tr>
<td>&#8220;0.0&#8243; + 0.0</td>
<td>number</td>
<td><strong>false</strong></td>
</tr>
<tr>
<td>&#8220;0E0&#8243;</td>
<td>number</td>
<td><strong>true</strong></td>
</tr>
<tr>
<td>0E0</td>
<td>number</td>
<td><strong>false</strong></td>
</tr>
<tr>
<td>&#8220;foo&#8221;</td>
<td>string</td>
<td>true</td>
</tr>
</tbody>
</table>
<p>Everything in Perl is true, except:</p>
<ul type="disc">
<li>the strings &#8220;&#8221; (the empty string) and &#8220;0&#8243; (the string containing only the character, 0), or any string expression that evaluates to either &#8220;&#8221; (the empty string) or &#8220;0&#8243;.</li>
<li>any numeric expression that evaluates to a numeric 0.</li>
<li>any value that is not defined (i.e., equivalent to undef).</li>
</ul>
<p>A very simple example of a real &#8220;if statement&#8221; would be:</p>
<pre name="code" class="php">
if ( $name ) {
    print "Non empty string";
}
else {
    print "Empty string";
}
</pre>
<p>Another example, to illustrate the syntax of the &#8220;if&#8221; statement:</p>
<pre name="code" class="php">
if ( $money &lt;= 0 ) {
    print "You are out of money";
}
elsif ( $money &gt; 1000000 ) {
    print "You are a millionaire";
}
else {
    print "You are probably better than I am";
}
</pre>
<p>Blocks of code in Perl are enclosed by curly braces {   }. They are <strong>always required</strong> inside a control structure (except for cases where we use idiomatic ifs &#8211; see more below).</p>
<p>Two things to mention:</p>
<p>1 &#8211; <tt>elsif</tt> spelling;<br />
2 &#8211; both <tt>elsif</tt> and <tt>else</tt> statements are optional.</p>
<p>Another conditional statement we need to mention is the <tt>unless</tt>. Its meaning is the opposite of an <tt>if</tt> statement. It will only execute a block of code if expression is NOT true.</p>
<p>Let&#8217;s look at an example:</p>
<pre name="code" class="php">
if  ( $num == 10 ) { #Usual if statement
    print "Number is equal to 10";
} else {
    print "Number not equal to 10";
}

# Unless statement that will execute the block of code below
# if number's value is not 10 (same thing as the else statement above)

unless ( $num == 10 ) {
    print "Number not equal to 10";
}
else {
    print "Number is equal to 10";
}
</pre>
<h3>Action based on statement test</h3>
<p>You can test a single statement and perform a pre-defined action in case it is true or another one if statement is false.</p>
<p>For example:</p>
<pre name="code" class="php">
    print "You are a man" if ($gender eq "M"); # parentheses are optional here, since only one expression is evaluated
</pre>
<p><code><br />
</code></p>
<p><code><br />
</code></p>
<h3>Ternary or Trinary Operator</h3>
<p>Like many other programming languages, Perl offers the ternary (aka trinary) operator &#8220;?:&#8221; which behaves just like if/elsif/else: </p>
<pre name="code" class="php">
print "You are a " . (($gender eq "M") ? "man" : "woman") . "n";
# read: if $gender eq "M" then "man" else "woman"

# or perhaps
($birthday == $today) ? print "Happy birthday!" : print "Have a good day";
</pre>
<p>Mimmic elsif this way:</p>
<pre name="code" class="php">
$month = (localtime)[4]; # fifth element of localtime in list context returns month, base 0;

print "The month is now " .
($month == 0) ? "January" :
($month == 1) ? "February" :
($month == 3) ? "March" :
                      "something other than Jan, Feb, or March";
</pre>
<h3>Operators</h3>
<p>Initially we will introduce the testing operators. They rely on a test being considered as true or false. Following you can see a few examples:</p>
<pre name="code" class="php">
$a == $b                      # Is $a numerically equal to $b?
# Beware: Don't use the = operator.
$a != $b                       # Is $a numerically unequal to $b?
$a eq $b                       # Is $a string-equal to $b?
$a ne $b                       # Is $a string-unequal to $b?
</pre>
<p>Perl also supports the logical operators &#8220;OR&#8221; and &#8220;AND&#8221;. The &#8220;OR&#8221; operator is represented by the &#8220;||&#8221; characters while the &#8220;AND&#8221; is represented by &#8220;&amp;&amp;&#8221; characters.</p>
<p>Lets go through a few examples:</p>
<pre name="code" class="php">
# If value of number is greater than 10 or lesser than 5
if ( ( $num &gt; 10 ) || ( $num &lt; 5 ) ) {
    ...
}

# If language is equal to "perl" and num is 10, or, if num is 0 (or has a "false" value)
if ( (( $language eq "perl" ) &amp;&amp; ( $num == 10 )) || !( $num ) ) {
    ...
}
</pre>
<h3>Loops</h3>
<p>We have several statements to perform iterations using Perl. Perl supports: <tt>while</tt>, <tt>until</tt>, <tt>do ... while</tt>, <tt>for</tt> and <tt>foreach</tt> statements.</p>
<h3><em>While</em></h3>
<p>Performs the iteration while the given expression is true. Syntax:</p>
<pre name="code" class="php">
while (expression) {
    instruction1;
    instruction2;
    ...
}
</pre>
<h3><em>Until</em></h3>
<p>It is the opposite of <tt>while</tt>. So take it as, in example:</p>
<pre name="code" class="php">
while (!(expression)) {
    instruction1;
    instruction2;
}

#same as
until (expression) {
   instruction1;
   instruction2;
}
</pre>
<h3><em>Do .. While</em></h3>
<p>Its functionality is almost the same as for the normal &#8220;while&#8221; statement, but with this kind of control structure you guarantee that the block of code will be executed at least once.</p>
<pre name="code" class="php">
do {
    instruction1;
    instruction2;
} while (expression);
</pre>
<h3><em>For</em></h3>
<p>It&#8217;s a C like style. Syntax:</p>
<pre name="code" class="php">
for (initialize; expression; increment/decrement) {
    instruction1;
    instruction2;
    ...
}
</pre>
<ul type="disc">
<li>The <em>initialize</em> statement is basically used to initialize the variable that will be used on the test statement. It can also be used anywhere in the block. Declare it with <tt>my</tt> to keep it private to the for block;</li>
<li><em>Expression</em> follows the same rule for <tt>if</tt> or <tt>while</tt>. It will be tested, and if its return is true, block code will be executed;<em></em></li>
<li><em>Increment/decrement </em>is then executed<em></em></li>
</ul>
<p>Real example:</p>
<pre name="code" class="php">
for ($i = 0; $i &lt; 10; $i++ ) {
    printf "Iteration number: %sn", $i;
}
</pre>
<p>Another good example (not using a numeric expression):</p>
<pre name="code" class="php">
for ( @names = ('John', 'Paul', 'Roger', 'David'); @names; shift(@names) ) {
    print "$names[0]n";
}

# Or work on 2 expressions at the same time
for ($i = 0, $j = 10; $i&lt;=10,$j&gt;=0; $i++, $j--) {
    print "$i    $jn";
}

# Or kick off an infinite loop
for ( ; ; ) {
    instruction1;
    instruction2;
}
</pre>
<h3><em>Foreach</em></h3>
<p>It is another control structure that allows iteration, but here you can iterate over an array.</p>
<p>Following you can see a few examples of it:</p>
<pre name="code" class="php">
@names = ('John', 'Paul', 'Roger', 'David');

#Passing through all names
foreach $name (@names) {
    printf "%sn", $name;
}
</pre>
<p>The scalar variable is optional to the <tt>foreach</tt> statement. So you can bypass it by doing:</p>
<pre name="code" class="php">
@names = ('John', 'Paul', 'Roger', 'David');

#Passing through all names
foreach (@names) {
    printf "%sn", $_;
}
</pre>
<p>If you don&#8217;t specify a scalar variable to get each iteration, then the default scalar ($_) will be used. Note that <tt>for</tt> can also be used as a synonym to <tt>foreach</tt> &#8211; same exact functionality, but without the <em>each</em> portion of the word.</p>
<h3><em>Loop flow control</em></h3>
<p>We have a few special commands to help us controlling the flow under a loop statement. Here we go.</p>
<p><tt>last</tt></p>
<p>It is similar to the &#8220;break&#8221; statement used on C programming language (as well as in several others). Tells Perl to skip the current loop statement, or even, to skip a labeled loop statement. Take a look at the example below:</p>
<pre name="code" class="php">
@names = ('fernando', 'smith', 'Mark', 'John');
foreach (@names) {
    last if $_ eq "John";
    print "Name is " . $_ . "n";
}
</pre>
<p><tt>next</tt></p>
<p><tt>next</tt> has the same function as the &#8220;continue&#8221; loop statement used in C. Used to force your loop statement to go to the next iteration. In example:</p>
<pre name="code" class="php">
@names = ('fernando', 'smith', 'Mark', 'John');
foreach (@names) {
    next if $_ eq "smith";
    print "Name is " . $_ . "n";
}
</pre>
<p>The example above will just force the &#8220;foreach&#8221; statement to read next iteration once &#8220;smith&#8221; is the value read from the &#8220;names&#8221; array.</p>
<p>If you need to work on multiple levels of loops, you can tell <tt>next</tt> and <tt>last</tt> which named block to work on:</p>
<pre name="code" class="php">
LINE: while (<STDIN>) {
	next LINE if /^#/;	# discard comments
	...
}
</pre>
<p style="text-align:right;"><a href="http://usestrict.net/2009/04/07/perl-crash-course-basic-regular-expressions/">« Basic Regular Expressions</a> | <a href="http://usestrict.net/2008/10/05/perl-crash-course/" target="_self">TOC</a> | Basic I/O »</p>
]]></content:encoded>
			<wfw:commentRss>http://usestrict.net/2009/04/perl-crash-course-control-structures/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

