Good job asking for feedback on your code. To elaborate on what
jwkrahn said about the range operator, the range operator is for *generating* a list of numbers, but what you want to do is iterate over an existing array.
So the range operator lets you say:
1..5
which is equivalent to the list:
1, 2, 3, 4, 5
So if, say, your ARGV array in the original example was ('add', 1, 7, 22, 5) then $ARGV[1]..$ARGV[$i] would evaluate to 1..5, ie: (1, 2, 3, 4, 5).
Echoing oko1's comment about a dispatch table being the way to go, here is how I would write your script:
use warnings;
use strict;
my %dispatch = (
add => sub { my $sum = 0; $sum += $_ for @_; $sum; },
multiply => sub { my $prod = 1; $prod *= $_ for @_; $prod; },
);
my $op = shift @ARGV;
print $dispatch{$op}->(@ARGV);
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.