הלינקייה: מגזין חודשי למפתחים

רוצה לשמוע על כל האירועים, המדריכים, הקורסים והמאמרים שנכתבו החודש ?
הלינקייה הינו מגזין חופשי בעברית שמשאיר אותך בעניינים.
בלי ספאם. בלי שטויות. פעם בחודש אצלך בתיבה.

Switch Blocks

Traditional perl did not have a switch statement. A core module named Switch became very popular and provided basic switch functionality.

Using the module, we were able to write code such as:

use Switch;
 
chomp (my $val = <>);
 
switch ($val) {
	case 1          { print "number 1\n" }
	case 2          { print "number 2\n" }
	case "a"        { print "word a\n"   }
	case /^abc/     { print "starts with abc\n"}
	else            { print "default case\n"}
}

As of perl 5.10, a new construct was introduced to the language - the given/when block. Given-When is a much more flexible switch statement. Here are some examples for using it:

use Modern::Perl;
 
given(<>) {
  when ( $_ < 10 )                 { say "small"};
  when ( ($_ >=10) && ( $_ < 20) ) { say "medium"};
  when ( $_ >= 20 )                { say "high"};
}

use Modern::Perl;
 
given(<>) {
  when ( $_ > 10 )   { say "Cool, more than 10"; continue}
  when ( $_ > 20 )   { say "Wow, more than 20"; continue}
  when ( $_ > 30 )   { say "Amazing ! more than 30"; continue}
}
 

Note the default behavior unlike c does not include a fallthrough. This is actually a good thing which prevents bugs.

course: