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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.