Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
I don't understand why this doesn't work. Where do I need to declare $myname? I thought I would have access to it at my print statement since I'm returning it in the subroutine.#!/usr/local/bin/perl use strict; myname(); print "my name is $myname\n"; sub myname { my $myname = "bill"; return $myname; }
I change that code a little bit in my experimenting to:
This prints out what I expect, but I notice that it works the same if I remove the return line from the subroutine. Why is this? Do I need to return the variable? What is the best way to go about using strict with subroutines?#!/usr/local/bin/perl use strict; my $myname = undef; myname(); print "my name is $myname\n"; sub myname { $myname = "bill"; return $myname; }
Since I'm already displaying my basic lack of understanding of local/global variables, when do I need to pass variables into a subroutine? I'm currently creating variables and using them later in subroutines without passing them in and having no problems. Is this the wrong way to do it?
Thanks for any help.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
(jeffa) Re: use strict and subroutines
by jeffa (Bishop) on Apr 02, 2001 at 19:53 UTC | |
|
Re: use strict and subroutines
by arhuman (Vicar) on Apr 02, 2001 at 19:52 UTC | |
by YoungPups (Beadle) on Apr 02, 2001 at 20:27 UTC | |
|
Re: use strict and subroutines
by davorg (Chancellor) on Apr 02, 2001 at 19:56 UTC | |
|
Re: use strict and subroutines
by busunsl (Vicar) on Apr 02, 2001 at 19:52 UTC |