Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl: Modify variable passed as param to subroutine

I need to modify a variable inside a routine, so it keeps the changes after leaving the routine. Here's an example:

$text = "hello";
&convert_to_uppercase($text);
print $text;

I want to see "HELLO" on the screen, not "hello".

The routine would be:

sub convert_to_uppercase($text){
  <something like $text = uc($text);>
}

I know how to do it in PHP, but it seems that the parameters are not changed the same way. And, I've been searching everywhere and I couldn't find a concrete answer.

like image 538
gonfer Avatar asked Feb 10 '26 14:02

gonfer


1 Answers

You really shouldn't use an ampersand & when calling a Perl subroutine. It is necessary only when treating the code as a data item, for instance when taking a reference, like \&convert_to_uppercase. Using it in a call hasn't been necessary since version 4 of Perl 5, and it does some arcane things that you probably don't want.

It is unusual for subroutines to modify their parameters, but the elements of @_ are aliases of the actual parameters so you can do what you ask by modifying that array.

If you write your subroutine like this

sub convert_to_uppercase {
    $_[0] = uc $_[0];
}

then it will do what you ask. But it is generally best to return the modified value so that the decision on whether to overwrite the original value can be taken by the calling code. For instance, if I have

sub upper_case {
    uc shift;
}

then it can be called either as

my $text = "hello"; 
$text = upper_case($text);
print $text;

which does as you require, and modifies $text; or as

my $text = "hello";
print upper_case($text);

which leaves $text unchanged, but returns the altered value.

like image 172
Borodin Avatar answered Feb 18 '26 06:02

Borodin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!