Search code examples
perlparameter-passingsubroutine

Perl how to modify parameter


How can the SOCKET recv function modify the value of the scalar $PDU directly? Usually this syntax is a pass by value not a pass by reference, I assumed up to now at least.

my $PDU; 
my $addr = $socket->recv($PDU, MAXBYTES);

I want to use this effect for my own purpose so best would be a handy test subroutine which depicts how this can be achieved.

Like:

my $PDU="orig";
sub test {
  my $par1=shift;
  $par1="test";
}
print "$PDU\n";

As you know this will result into "orig" not "test".

Thank you in advance.

Kind regards, Hermann


Solution

  • Your function should be well documented when having such behavior,

    my $PDU="orig";
    sub test {
      $_[0] = "test";
    }
    
    test($PDU);
    print "$PDU\n";
    

    or

    sub test {
      my ($par1) = map \$_, @_;
    
      $$par1 = "test";
    }
    

    output

    test