perlでのswitch文

9/8追記

先輩から、Switchモジュールはバグが多く現在では非推奨モジュールになっているというアドバイスいただきました。

以下、5.12.0ドキュメント(perl5120delta - perldoc.perl.org)より引用


You can silence these deprecation warnings by installing the modules in question from CPAN. To install the latest version of all of them, just install Task::Deprecations::5_12 .

Class::ISA
Pod::Plainer
Shell
Switch

Switch is buggy and should be avoided. You may find Perl's new given/when feature a suitable replacement. See Switch statements in perlsyn for more information.


Switchモジュールを用いたサンプルは残しておきますが、

5.10以降はgivenを用いたほうがいいそうなのでそちらをお使いください。


私の環境では5.8.8だったので、if-else文に置き換えました。

追記終わり



perlではモジュールを利用しないとswitch文が使えないということを知りました


これまで使ってきた言語ではデフォルトでswitch文が使えたのでこれは少し意外でした


switch文を使うにはSwitchモジュールを呼び出す必要があります


以下、case文を使いたいだけの意味のないサンプル


forで回して無理やりswitch文を使ってます


phpでは、caseに該当しないものは「default」で表していましたが、perlのSwitchモジュールでは「else」を用います

サンプルコード
#usr/bin/perl
use strict;
use warnings;
use Switch;

for (1..10) {
    switch ($_) {
        case 1 {
            print "hello\n";
        }
        case 2 {
            print "good\n";
        }
        else {
            print "this value is $_\n";
        }
    }
}
結果
hello
good
this value is 3
this value is 4
this value is 5
this value is 6
this value is 7
this value is 8
this value is 9
this value is 10


また、perl 5.10以降は標準で組み込まれている「given」を用いることで同様の処理が可能なようですね

givenを用いたサンプルコード
#!usr/bin/perl
use strict;
use warnings;
use 5.10.0;

for (1..10) {
    given ($_) {
        when (1) {
            say "hello";
        }
        when (2) {
            say "good";
        }
        default {
            say "this value is $_";
        }
    }
}


「say "xxx"」を使うことで「print "xxx\n"」の際に必要だった改行コードの省略が可能です

参考にさせていただいたサイト