dee00zee has asked for the wisdom of the Perl Monks concerning the following question:

I try to use subroutine in my program but it
didn't return the value that I want.What is wrong
with my code?

example:
sub coor { my ($a,$b); $f=$a+109; $g=$b+5; @in=($f,$g); } ###################################################### #MAIN PROGRAM &coor("1","2"); @y1_opp=&coor; print "@y1_opp\n";
The output I get is $f=109 and $g=5
My subroutine did not work :(

Janitored by Arunbear - added code tags, as per Monastery guidelines

Replies are listed 'Best First'.
Re: subroutine..help
by Zaxo (Archbishop) on Oct 29, 2004 at 05:59 UTC

    You're not making any use of the arguments in your subroutine, so $a, $b are both zero.

    You shouldn't rely on global variables to convey information in and out of a subroutine. Here is how your code might be better written,

    sub coor { my ($c, $d) = @_; return ( $c + 109, $d + 5 ); } my @y1_opp = coor( 1, 5); print "@y1_opp\n";
    I've renamed $a and $b since they are sacred to sort in Perl.

    After Compline,
    Zaxo

      Just personal preference here, but I prefer to use "shift" instead of picking off arguments from @_, like this:
      sub coor { my $c = shift; # get 1st argument my $d = shift; # get 2nd argument return ( $c + 109, $d + 5 ); }
      And, the OP should use "use strict;" and either "-w" on the first perl line or "use warnings;".
Re: subroutine..help
by TedPride (Priest) on Oct 29, 2004 at 09:37 UTC
    use strict; use warnings; my @y1_opp = &coor(1,2); print "@y1_opp\n"; sub coor { return ($_[0]+109, $_[1]+5); }
Re: subroutine..help
by gube (Parson) on Oct 29, 2004 at 14:36 UTC

    If u wish please, try this code

    sub coor { my ($a,$b)=@_; $f=$a+109; $g=$b+5; return($f,$g); } @y1_opp=&coor("1","2"); print "@y1_opp\n";
Re: subroutine..help
by artist (Parson) on Oct 29, 2004 at 15:14 UTC
    You have already got the answer:
    You should have thought: How you are getting the values inside the subroutine which is passed to the subroutine.
    What you have :my($a,$b);
    What you Should have: my($a,$b) = @_;