Perl Learning - 18 (unless, until, elsif, for)

unless expression: when condition is false execute the block.
 
unless($fred=~/^[A-Z_]\w*$/i){
 print "The value of \$fred doesn't look like a perl identifier name.\n";
}
 
It's the same as written like this:
 
if($fred=~/^[A-Z_]\w*$/i){
 # do nothing
}else{
 print "The value of \$fred doesn't look like a perl identifier name.\n";
}
 
Or:
 
if(!($fred=~/^[A-Z_]\w*$/i)){
 print "The value of \$fred doesn't look like a perl identifier name.\n";
}
 
until expression: when condition is false execute the loop.
 
until($j>$i){
 $j *= 2;
}
 
if expression can be written without a block of {}
 
print "$n is a negative number.\n" if $n < 0;
 
Perl execute 'if $n < 0' first, if it's true then execute the print expression, if false do nothing.
 
Those styles are all popular in Perl:
 
&error("Invalid input") unless &valid($input);
$i *=2 until $i > $j;
print " ", ($n += 2) while $n < 10;
&greet($_) foreach @person;
 
If there are more than one expression, better to write them in {} blocks.
 
elsif expression:
 
if(condition){
 do something;
}elsif(condition){
 do something;
}elsif(condition){
 do something;
}else{
 do something;
}
 
my $bedrock=42;
$bedrock++;
 
my @people=qw{ Fred barney Fred wilma dino barney Fred pebbles };
my %count;
$count{$_}++ foreach @people;
 
++ means +1 byself, undef++ gets 1
 
my $n=++$m;
$m add 1, then give value to $n.
 
my $n=$m++;
give value to $n, then $m add 1.
 
for (init;test;increment){
 body;
 body;
}
 
for(i=1;$i<=10;$i++){
 print "I can count to $i!\n";
}
 
Any of init, test, increment can be empty, but the symbol ';' should be there.
 
for($_="bedrock";s/(.)//;){ # whenever s/// successes, loop continue
 print "One character is: $1\n";
}
 
for(1..10){
 print "I can count to $_!\n":
}
 
Here 'for' is the same as foreach. for and foreach are the same in Perl, Perl will judge by the contents in (). If there're ';' in () then it's for, otherwise it's foreach.
 
 

你可能感兴趣的:(perl,learning)