Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

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; }


Comment on Re^2: calling subroutines
Download Code
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.


    Dave

      Tnx man :) Now I understand the problem.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1057999]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (8)
As of 2014-09-18 02:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (105 votes), past polls