Decode Funktion in Perl

I missed the decode function from PL/SQL in Perl so I wrote it, the parameters look like this (‘variable’, ‘serach1’, ‘return1’ … ‘serach1’, ‘return1’, ‘default return’);

#!/usr/bin/perl
use strict;
#tests
print decode("1","1","a","2","b","X").$/;
print decode("2","1","a","2","b","X").$/;
print decode("3","1","a","2","b","X").$/;

#sub
sub decode {
    my @dec = @_;
    if($#dec%2==0){print "Number of arguments invalid !";exit;}
    for(my $i = 1;$i <= ($#dec-1);$i += 2){
        if($dec[0] eq $dec[$i]){return($dec[$i+1]);}
    }
    return($dec[$#dec]);
}

As expected ‘1’ is decodet to ‘a’, ‘2’ to ‘b’ and the default is ‘X’.

sh-4.2# perl main.pl
a
b
X

 

Leave a Reply

Your email address will not be published.

nineteen − 5 =