dreman has asked for the wisdom of the Perl Monks concerning the following question:

Can you pass arguments to a sub-routine, if so,how? thanks. dreman

Replies are listed 'Best First'.
Re: input variables
by dvergin (Monsignor) on Dec 11, 2001 at 00:28 UTC
    This is a legitimate question for a beginner. But it is quite basic in any introductory book or documentation. In the long run you will get a lot more help here at the monestary if you demonstrate that you have done some work or study on your own. Describe what you have read and where you are stuck. Or better yet, show us some code that illustrates your best attempt to solve your own question.

    For subroutines and their arguments, the general idea is this: you can call a sub with values this way: mysub($val1, $val2, etc). Then in the subroutine itself, those values are available in the special array called @_.

    Here's some code to show some alternatives for accessing those values:

    #!/usr/bin/perl -w use strict; sub mysub { # the args are in @_ my $bigness = $_[0]; # copy one val my ($size, $color, $style) = @_; # or grab them all my $proportions = shift; # or shift; @_ is implicit uc($_[1]); # or use @_ directly # do stuff with $bigness, $size, etc. } mysub('big', 'blue', 'fuzzy');

    Because any action on the values in @_ changes their values back where they were called, many people follow the rule of not doing anything with or to the @_ values directly (e.g. $_[2]) unless the purpose of the subroutine is to directly change the parameter in question. Instead they use one of the first three methods above to copy the values and then work with that.

    You will find a lot of help for these basic issues here at Perl Monks in the Library and in Tutorials. In particular a quick visit to the Library yields perlman:perlsub on subroutines. (I suggest you ignore material relating to prototypes for now.)

    ------------------------------------------------------------
    "Perl is a mess and that's good because the
    problem space is also a mess.
    " - Larry Wall