So I just noticed something cool. As long as the logic's not too complex, you can use a ternary statement to replace a switch statement in Perl. I mean, you COULD use the Switch statement, but you'd have to have the Switch.pm module on the machine running the script. If you were to instead use a ternary operator, you could do the logic with nothing more than Perl's native language methods.
use strict;
use warnings;
my $testChoice;
my $selection;
$selection = shift;
$testChoice = ($selection == 1) ? "one" :
($selection == 2) ? "two" :
($selection == 3) ? "three" :
"invalid choice" ;
print $selection, ", ", $testChoice;
I could see such logic working particularly well for a menu system.
Edit: Shit, why hardcode a value for selection? You can shift and pass it through the command line when testing out the script running it. Doing so made me realize that you can test for multiple conditions with the right syntax.
use strict;
use warnings;
my $testChoice;
my $selection;
$selection = shift;
$testChoice = ($selection == 1 || $selection == 2) ? "one" :
($selection == 3 || $selection == 4) ? "two" :
($selection == 5 || $selection == 6) ? "three" :
"invalid choice" ;
print $selection, ", ", $testChoice, "\n";
Yeah, this works pretty slickly. In fact, I can show you some sample tests from my machine.
b-man@B-Man-Linux:~/Desktop$ perl test.pl 0
0, invalid choice
b-man@B-Man-Linux:~/Desktop$ perl test.pl 1
1, one
b-man@B-Man-Linux:~/Desktop$ perl test.pl 2
2, one
b-man@B-Man-Linux:~/Desktop$ perl test.pl 3
3, two
b-man@B-Man-Linux:~/Desktop$ perl test.pl 4
4, two
b-man@B-Man-Linux:~/Desktop$ perl test.pl 5
5, three
b-man@B-Man-Linux:~/Desktop$ perl test.pl 6
6, three
b-man@B-Man-Linux:~/Desktop$ perl test.pl 7
7, invalid choice
So you can take this logic one step further and do multiple variable assignment with your ternary statement.
use strict;
use warnings;
my $testChoice;
my $testChoice2;
my $selection;
$selection = shift;
($testChoice, $testChoice2) = ($selection == 1 || $selection == 2) ? ("one", "foo") :
($selection == 3 || $selection == 4) ? ("two", "bar") :
($selection == 5 || $selection == 6) ? ("three", "derp") :
"invalid choice" ;
print $selection, ", ", $testChoice, , ", ", $testChoice2, "\n";
When you run this, you get the following results:
b-man@B-Man-Linux:~/Desktop$ perl test.pl 1
1, one, foo
b-man@B-Man-Linux:~/Desktop$ perl test.pl 3
3, two, bar
b-man@B-Man-Linux:~/Desktop$ perl test.pl 5
5, three, derp
I'm not quite sure how far you can take this thinking in other languages because I haven't tested it. However, I now know that it works in Perl, and that's awesome.