Raphael Brunner wrote:
>
> On Mon, Oct 16, 2006 at 07:36:13PM +0800, Jeff Pang wrote:
>>
>> Raphael Brunner wrote:
>>>
>>> eg:
>>>
>>> use strict;
>>> my $var = 20;
>>>
>>> print "$var\n";
>>> &routine;
>>> exit;
>>>
>>>
>>> sub routine {
>>>    print "$var\n";
>>> }
>>>
>>
>> Hi,you can do it by passing the vars to the subroutine like:
>>
>> my $var = 20;
>> &routine($var);
>>
>> sub routine {
>>     my $var = shift;
>>     print $var;
>> }
>
> Thanks for your answer!
>
> But, my problem is, i must see this variable after the call of the sub.
> I'm sorry for the first example, it was inaccurate. But this is ok (I
> think) :) (because I have a lot of variables, which I must change in the
> sub, I want to define they as "global" inside my parent-routine (in the
> example: the programm, but by me: the parent-sub)).
>
> Thanks for all, Raphael
>
> eg:
>
> use strict;
> my $var = 20;
>
> print "before: $var\n";
> &routine;
> print "after: $var\n";
> exit;
>
>
> sub routine {
>    $var += 1;
> }

(Please bottom-post your replies so that the thread remains comprehensible.
Thanks.)

I don't understand what problem you're having Raphael. Both of the examples that
you've posted should do what you say you want. What's wrong with those?

You've been given a lot of useful advice which you should take heed of, in
particular that you shouldn't use the ampersand when calling a subroutine.
There's also no need for the exit call in your program as there is nothing
executable after it.

I would add that you can write a subroutine that modifies its actual parameters
without passing them by reference if you adjust the @_ parameter array directly,
as in the code below. There's nothing wrong with modifying global variables like
this as long as it's done clerly and coherently and in moderation.

HTH,

Rob


use strict;
use warnings;

my $var = 20;

print "before: $var\n";
increment($var);
print "after: $var\n";

sub increment {
  $_[0]++;
}

**OUTPUT**

before: 20
after: 21


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to