Loading ...
Sorry, an error occurred while loading the content.
 

RE: [PBML] Re: subroutine - variable scope:

Expand Messages
  • Gergely Brautigam
    No it should not. You see $answer is the inner value of the adder sub. It s like this: sub add { my $result = $_[0] + $_[1]; return $result; } sub
    Message 1 of 5 , Mar 19, 2008
      No it should not. You see $answer is the inner value of the adder sub.
      It's like this:



      sub add {

      my $result = $_[0] + $_[1];

      return $result;

      }



      sub somethingelse {

      my $thisresult = &add (1, 2);

      print $thisresult;

      }



      These are two separate values. You are not in anyway forced to use the
      same name or value that the other sub returns. Look a perl tutorial
      about values, and returns :)



      From: perl-beginner@yahoogroups.com
      [mailto:perl-beginner@yahoogroups.com] On Behalf Of draktrax
      Sent: Wednesday, March 19, 2008 6:10 AM
      To: perl-beginner@yahoogroups.com
      Subject: [PBML] Re: subroutine - variable scope:



      --- In perl-beginner@yahoogroups.com
      <mailto:perl-beginner%40yahoogroups.com> , "Jeff Shu" <santa98bn@...>
      wrote:
      >
      > hello everyone:
      > I want to pass two numbers to a subroutine. within the subroutine
      add
      > two numbers and return the sum to calling function.
      >
      > I have two files my_main.pl and my_sub.pl. the parameter's value
      > didn't pass to the subroutine. sum's value is always
      > zero.
      >
      > I think i may not understood the value scope well in perl. Please
      > check my code and tell me how can I make this work.
      > Thanks for your help!
      >
      > my_main.pl
      >
      > #!/usr/bin/perl
      >
      >
      > use strict;
      > use warnings;
      >
      > require "my_sub.pl";
      >
      > my $x = 5;
      > my $y = 7;
      >
      > my $result = addition($x, $y);
      > print $result;
      >
      >
      >
      > my_sub.pl file
      >
      > #!/usr/bin/perl
      > #a sub-routine used in my_main.pl
      >
      > #Illegal character in prototype for main::addition $a, $b at
      > my_sub.pl line 11
      > #
      >
      > use strict;
      > use warnings;
      >
      > my $num1 = 0;
      > my $num2 = 0;
      >
      > sub addition($num1,$num2)
      > {
      > my $answer = $num1 + $num2;
      > print "\$answer is: $answer.\n";
      > return $answer;
      >
      > }
      >
      > 1;
      >I'm a newbie at this but, if the sub returns '$answer'
      shouldn't the main use '$answer' rather than '$result' ?





      [Non-text portions of this message have been removed]
    Your message has been successfully submitted and would be delivered to recipients shortly.