Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW

Re^2: calling subroutines

by bobosm (Initiate)
on Oct 12, 2013 at 16:16 UTC ( #1057999=note: print w/replies, xml ) Need Help??

in reply to Re: calling subroutines
in thread calling subroutines

I write like that, but it is error: Use unitialized num1 in additional

for ( 1 .. 5 ) { my $num1 = int(rand(10)); some(); } sub some { print "Enter a number: \n"; #chomp (my $num1 = <STDIN>); my $num1; my $num2 = 2; my $result; $result = $num1 + $num2; print "result is: $result\n"; #return result; }

Replies are listed 'Best First'.
Re^3: calling subroutines
by davido (Archbishop) on Oct 12, 2013 at 16:27 UTC

    Passing variables into a subroutine through osmosis (except for specific situations that you don't need to worry about yet) is a terrible habit to get into.

    To remedy your immediate problem, remove the line from your sub, "my $num1;", because it's creating a lexical variable inside the sub that masks the variable created in your for loop. But, while that will fix the immediate problem, it will start you down the wrong path. What you should be doing is passing parameters into your subroutine like this:

    my $value = "whatever"; some($value); sub some { my( $param ) = @_; print "$param\n"; }

    ...or use shift, or any of the other means demonstrated when you read the document "perlsyn", by typing perldoc perlsyn on your local system with Perl installed.


      Tnx man :) Now I understand the problem.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1057999]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (4)
As of 2017-10-21 11:26 GMT
Find Nodes?
    Voting Booth?
    My fridge is mostly full of:

    Results (269 votes). Check out past polls.