Taking that hash idea a bit further, you could end up at a dispatch table, something like the following:
#!usr/bin/perl use strict; use warnings; sub req_args { my $nArgs = @ARGV; die "$_[0] argument(s) required but $nArgs given!\n" if $_[0] != $nArgs; } my $pi=3.141592654; my %dispatch = ( tri => { area => sub { req_args(2); return 0.5*$ARGV[0]*$ARGV[1]; + }, peri => sub { req_args(3); return $ARGV[0]+$ARGV[1]+$ARGV +[2]; }, hypo => sub { req_args(2); return sqrt($ARGV[0]*$ARGV[0]+ +$ARGV[1]*$ARGV[1]); }, }, cir => { area => sub { req_args(1); return $ARGV[0]*$ARGV[0]*$pi; + }, #radius peri => sub { req_args(1); return $pi*$ARGV[0]; + }, #diameter hypo => sub { die "Option 'hypo' only allowed for triangl +e." }, }, rec => { area => sub { req_args(2); return $ARGV[0]*$ARGV[1]; + }, peri => sub { req_args(2); return 2*($ARGV[0]+$ARGV[1]); + }, hypo => sub { die "Option 'hypo' only allowed for triangl +e." }, }, sqr => { area => sub { req_args(1); return $ARGV[0]*$ARGV[0]; + }, peri => sub { req_args(1); return 4*$ARGV[0]; + }, hypo => sub { die "Option 'hypo' only allowed for triangl +e." }, }, ); die "You need to specify at least 3 args." if @ARGV < 3; # $what to calculate on $which type of figure my ($which, $what) = (shift, shift); die "Unknown type '$which' of figure." unless exists $dispatch{$wh +ich}; die "Unknown type '$what' of calculation." unless exists $dispatch{$wh +ich}{$what}; print "The answer is ", $dispatch{$which}{$what}(), ".\n";
-- Hofmator
In reply to Re: Re: Can't grab $ARGV[n]
by Hofmator
in thread Can't grab $ARGV[n]
by OxYgEn
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |