http://www.perlmonks.org?node_id=808698

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

Hi everyone!

I have some problems with perl subroutines, or being more specific, I cannot figure out why they are not working as they should.

Here is a tiny code snippet as a sample:
sub doubleWord($word) { return $word.$word; } print &doubleWord('hello');

I was hoping that output would be the string 'hellohello', but turns out there is no output at all. I run the script and nothing happens. No errors, no warnings, nothing.

Where is the catch or what am I doing wrong? I'd really like to understand the subroutine's logic.

Replies are listed 'Best First'.
Re: Subroutine's behavior
by keszler (Priest) on Nov 23, 2009 at 01:15 UTC
    perlsub
    use strict; sub doubleWord { my $word = shift; return $word.$word; } print doubleWord('hello');
Re: Subroutine's behavior
by tford (Beadle) on Nov 23, 2009 at 01:38 UTC

    The reply above mine pretty much says it all. However, you might be wondering what the shift is for.

    The shift function takes an array as input, and "shifts" off the first element of the array. Then it returns that element, leaving the array one element shorter.

    For example,

    my @array = (2,3,4); my $value = shift(@array); # now the array contains (3,4) print "value is $value";

    Now, if you don't specify an array to use as input, the shift function works on the "default array" called @_.

    The last important thing to know is that anytime you call a Perl subroutine, you only ever call it with a flat array of arguments. Within the scope of the subroutine, those arguments are automatically assigned to the @_ array.

    Thus shift shifts the first argument off the argument array, and assigns it's value to the variable $word, which is local to the subroutine.

    Hope this helps!

    ~tford

Re: Subroutine's behavior
by toolic (Bishop) on Nov 23, 2009 at 01:31 UTC
    what am I doing wrong?
    You should always use strict and warnings because you would have gotten warnings about your code.
Re: Subroutine's behavior
by doug (Pilgrim) on Nov 23, 2009 at 14:47 UTC

    As has been pointed out, you've got your subroutine arg passing broken. strict and warnings should be your friends.

    If I remember correctly, perl6 will use something like this. Maybe you mean to be running that instead of standard perl5? Or you've been reading perl6 docs and don't know that this is one of the many changes?

    - doug