
Laurent_R
Enthusiast
Nov 1, 2012, 2:39 AM
Post #14 of 14
(1311 views)
|
|
Re: [griever92] Using Arguments with Subroutines
[In reply to]
|
Can't Post
|
|
So if i'm understanding this correctly, I will need to define the argument into a variable, prior to passing said variable to a subroutine, yes? Is my problem simply that I have been trying to pass the CLI argument directly to the sub, without referencing it in the main? You don't have to, but it will often be clearer if you do, especially if you give sensible names to your variables. But you have the right to write in the main section of your program:
my $foo = some_function($ARGV[0], $ARGV[2]); or even:
my $bar = some_other_function(@ARGV); It is however usually clearer to state what the arguments are by storing them in appropriately named variables:
my ($width, $length) = @ARGV; my ($perimeter, $area) = compute_rectangle($width, $length); And the function definition:
sub compute_rectangle { my ($local_w, $local_l) = @_; my $local_perim = 2 * ($local_w + $local_l); my $local_area = $local_w * $local_l; return ($local_perim, $local_area); } (I would normally not call my variables $local_w, $local_l, etc., but I wanted to insist here that they are local copies of $width, $length, etc., available only within the function. I am not even sure I would write a function for such easy calculations, unless the same function were used somewhere else in the program.)
|