in reply to Dynamically changing the value of a passed variable into a sub

You'll need to pass a reference to the scalar variable as a parameter to the subroutine.

TimeStamp(\$data_created); sub TimeStamp { my ($dataRef) = @_; if ($$dateRef =~ /(\d{4})(\d{2})(\d{2})/) { $$dateRef = "$2/$3/$1"; } else { warn("..."); } }

Since Perl has call-by-value semantics, i.e. a copy of the variable is passed to the subroutine rather than the value itself, you have to pass the address of the variable (i.e. \$date_created) to the subroutine.

In the subroutine, you manipulate the value $$dateRef which is stored at address $dataRef.

Hope this helps, -gjb-

  • Comment on Re: Dynamically changing the value of a passed variable into a sub (see node below, this one got submitted in error)
  • Select or Download Code

Replies are listed 'Best First'.
Re: Re: Dynamically changing the value of a passed variable into a sub (see node below, this one got submitted in error)
by jdporter (Paladin) on Nov 04, 2002 at 21:11 UTC
    gjb is correct in suggesting that the variable can be passed by reference, so that the sub may modify it.

    However, his assertion that arguments are passed by value is not quite correct. In fact, arguments are passed "by alias", which is essentially under-the-hood references.

    When the docs say that the sub receives the argument list in @_, what they really mean is that each element of @_ is an alias to the actual argument.

    This means that modifying an element of @_ modifies the actual argument.

    So -- as a possible alternative -- instead of doing

    modify( \$val ); sub modify { my $ref = shift; $$ref ++; # or whatever }
    you can in fact do this:
    modify( $val ); sub modify { $_[0] ++; # or whatever. }
    However, just because you can do this, doesn't mean you should. This technique is considered by many to be Bad Programming.

    The other issue to be aware of -- for future reference -- is that constant values can not be modified*. If you try, perl will barf.

    *This is always true**, but having the modification down in a subroutine can make you forget.

    **That is, constant values can't be modified within Perl code. By calling low-level (C) code, e.g. via XS, anything is possible.