Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 [Perl5-tut] Perl Intro: Conditionals
Index -> General Programming
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
wtd




PostPosted: Fri Sep 23, 2005 1:25 am   Post subject: [Perl5-tut] Perl Intro: Conditionals

If

This looks pretty much like most languages. A notable differences is that the curly braces are required. There is no "shortcut" syntax.

Perl:
if ($foo == 42)
{
   print "Hello\n";
}


Elsif and else

As in other languages, there are fallback clauses.

Perl:
if ($foo == 42)
{
   print "Hello\n";
}
elsif ($bar == 38)
{
   print "Yo\n";
}
elsif ($baz == 56)
{
   print "Wooble!\n";
}
else
{
   print "Ninja!!!\n";
}


Unless

"if" has a counterpart. It's called unless.

For instance, instead of:

Perl:
if ($foo != 42)
{
   print "Hello\n";
}


We can write:

Perl:
unless ($foo == 42)
{
   print "Hello\n";
}


Postfix

For very simple tests, we can use "if" and "unless" in a postfix form.

Perl:
print "Hello\n" unless $foo == 42;


The ternary operator

This also functions pretty much the same way it does in other languages.

Perl:
$foo == 42 ? "Hello" : "World";


If the test in front of the question mark is true, then the first expression is evaluated. If not, the second expression is evaluated. The expressions are separated by a colon.

Comparison operators

Strings and numbers use different comparison operators in Perl5.

For numbers, we can use the classic: ==, !=, <, >, <=, >=, and for a three way comparison: <=>.

For strings, the corresponding operators are: eq, ne, lt, gt, le, ge, and cmp.
Sponsor
Sponsor
Sponsor
sponsor
Display posts from previous:   
   Index -> General Programming
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 1 Posts ]
Jump to:   


Style:  
Search: