use strict; use warnings; use feature qw( switch say ); sub test_it { my $value = shift; given($value) { when(/aaa/) { return 'wanna' } when(/bbb/) { return 'be' } when(/ccc/) { return 'startin' } default { return 'somethin' } } } foreach my $str (qw[testaaa testbbb testccc testddd]) { say test_it($str); }
I don't know how Perl6 addresses this, but e.g. in (PLT) Scheme the explicit returns aren't needed:use strict; use warnings; use feature qw( switch say ); use Getopt::Long; my $tester = 'test_it'; GetOptions("test=s" => \$tester); sub test_it { my $value = shift; given($value) { when(/aaa/) { return 'wanna' } when(/bbb/) { return 'be' } when(/ccc/) { return 'startin' } default { return 'somethin' } } } sub test_it2 { my $value = shift; do { no warnings; given($value) { when(/aaa/) { 'wanna' } when(/bbb/) { 'be' } when(/ccc/) { 'startin' } default { 'somethin' } } }; } sub test_it3 { my $value = shift; do { local $_ = $value; if(/aaa/) { 'wanna' } elsif(/bbb/) { 'be' } elsif(/ccc/) { 'startin' } else { 'somethin' } }; } foreach my $str (qw[testaaa testbbb testccc testddd]) { say $main::{$tester}->($str); }
#lang scheme (define (test-it value) (match value [(regexp #rx"aaa") "wanna"] [(regexp #rx"bbb") "be"] [(regexp #rx"ccc") "startin"] [_ "somethin"])) (for ([str '("testaaa" "testbbb" "testccc" "testddd")]) (printf "~a~n" (test-it str)))
In reply to Re: Would you use a switch instead?
by Arunbear
in thread Would you use a switch instead?
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |