
japhy
Enthusiast
Aug 31, 2000, 3:48 AM
Post #2 of 2
(119 views)
|
|
Re: Passing arguments to subroutines
[In reply to]
|
Can't Post
|
|
Check the perlsub documentation on how to write functions. Aside from that, if you want to pass values to a function, you do it like so: <BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR> function($this, @that, %those); </pre><HR></BLOCKQUOTE> Arguments are then stored in the @_ array in the function. The argument list is flattened -- meaning: <BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR> $name = "Jeff"; @langs = qw( Perl C++ Python ); person(@langs, $name); sub person { my (@languages, $person) = @_; print "$person uses: @languages\n"; } </pre><HR></BLOCKQUOTE> Does not pass @langs as one argument, but rather unrolls the list as if I had said <BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR> person("Perl", "C++", "Python", "Jeff"); </pre><HR></BLOCKQUOTE> In addition, saying <BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR> (@this,$that) = (1,2,3,4); </pre><HR></BLOCKQUOTE> Puts (1,2,3,4) in @this, and leaves $that empty -- so our function should PROBABLY be rewritten as: <BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR> person($name, @langs); sub person { my ($who, @proglangs) = @_; print "$who uses: @proglangs\n"; } </pre><HR></BLOCKQUOTE> Anyway, arguments are in @_. You can access them individually via $_[0], $_[1], etc. IF YOU MODIFY $_[$x], then the ACTUAL ARGUMENT YOU PASSED GETS MODIFIED. Example: <BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR> $name = "jeff"; change($name); print $name; # Ffej sub change { $_[0] = ucfirst reverse $_[0] } </pre><HR></BLOCKQUOTE> That's all for now. ------------------ Jeff "japhy" Pinyan -- accomplished author, consultant, hacker, and teacher
|