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

Say I have a sub called &reverse_word that, well, reverses whatever word I send to it. How do I send that 'word' to the sub routine and how do I go about returning a it (ie, the word reversed)?
Could I do something like this:
$word = "cheese"; <BR> $reversed = &reverse_word($word); <BR>
-thanks

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How do I pass variables to my subroutines?
by Fastolfe (Vicar) on Jan 24, 2001 at 22:24 UTC
    Please read perlsub, perhaps perlsyn, and a good introductory Perl book such as "Learning Perl". Briefly, arguments to subroutines are passed via the special @_ array (see perlvar). Use shift to pull these out one-at-a-time, access elements of this array individually, or pull them all out at once via a list assignment.

    Originally posted as a Categorized Answer.

Re: How do I pass variables to my subroutines?
by Fastolfe (Vicar) on Jan 24, 2001 at 22:25 UTC
    Additionally, this specific task can be solved by making use of the built-in reverse function, which, in a scalar context, reverses the string character-wise, which seems to be what you want. Also read perlfunc.

    Originally posted as a Categorized Answer.

Re: How do I pass variables to my subroutines?
by kilinrax (Deacon) on Jan 24, 2001 at 22:35 UTC
    Well, for a start, you can use 'scalar reverse $word' to reverse a word.
    If you were using '&reverse_word' as simply an example, then I'd recommend reading up on shift and return;
    sub reverse_word() { my $word = shift; my $reversedword = scalar reverse $word; return $reversedword; }
    or, more consisely:
    sub reverse_word() { return scalar reverse shift; }

    Originally posted as a Categorized Answer.