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

call-by-value

Expand Messages
  • Jeff Shu
    Hi everyone: I wrote a sample script and want to see how call-by-value works. my understanding is that once variable is be localized by my function, a copy of
    Message 1 of 1 , Mar 12, 2007
    • 0 Attachment
      Hi everyone:

      I wrote a sample script and want to see how call-by-value works.

      my understanding is that once variable is be localized by my function,
      a copy of the value of argument is being send to function/subroutine.

      Here is my sample script:


      use strict;
      use warnings;

      sub addition
      {
      #$_<0> = $_<0> + 1;

      $a = $a + 1;
      print "in subroutine \$a value changed to: $a\n";

      }

      my $a = 5;

      &addition($a);

      print "after subroutine the value of \$a is: ", $a;

      I tried two options
      a) I used @_ arrary to access argument and increment it by 1. the
      result is that value of '$a' changed in main block as well.

      b) I used $a = $a + 1 in subroutine, the output is

      "Use of uninitialized value in addition (+) at
      C:\CIS068E\chap10\call_by_value.pl line 12.
      in subroutine $a value changed to: 1
      after subroutine the value of $a is: 5 " I am sure if option b)
      demonstrated purpose of call-by-value.

      Plase give me some suggestion on why a) didn't work,
      wheather b) is a right approach to demonstrate the purpose of
      call-by-value. Thanks!

      Jeff
      3-12-07
    Your message has been successfully submitted and would be delivered to recipients shortly.