Modify a string passed by reference in perl

I don’t know why I feel the need to write this down, but I was having a slow brain day and needed to actually sit and think about using string references within a perl subroutine!

my $string = "STRINGY";

print "Before: $string\n";
modify_string(\$string);
print "After: $string\n";

sub modify_string
{
my ($string_ref) = @_;
my $length = length($$string_ref);
$$string_ref .= "-$length";
}

This tries to demonstrate two things. Firstly using the string reference (i.e. into the length command and secondly modifying the string itself (appending a dash and the length of the string to it). Don’t worry about the “-$length” bit — it’s not trying to do anything cleverer than append to the string… :)

Technorati Tags: ,