substr() as subroutine argument

Answer

The elements of @_ are aliases not copies of the arguments.

sub foo { $_[0] = 'Cooked' };
my $q='Raw';
foo($q);
print "$q\n"; # Prints 'Cooked'

substr() does not return a string. It returns a special thing - an SV with substr magic. If you use substr() in an rvalue context you can ignore this subtlty.

But if you make a reference or an alais to the value returned by substr() you cannot or, as you have found, strange things happen.

  my $s='xxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
  my $x = \substr($s,10,10); # Ref to SV with substr magic
  $s = '0123456789Wierd, eh??';
  print "$$x\n"; # Prints 'Wierd, eh?';
  $$x= 'Just totally crazy';
  print "$s\n"; # Prints '0123456789Just totally crazy?'

  $s = "field1       field2 field3";
  $$x =~ s/\s//g;
  print "$$x\n"; # Prints 'field2fiel'

Brian McCauley's original post

Next