Reputation: 794
Here is my code:
#!/usr/bin/perl -w
my $name = "mark";
my $nameRef = \$name;
print "${$nameRef}\n";
print "$nameRef\n";
my $ref = $nameRef + 1;
$$ref = "antony";
print "$ref\n";
print "$$ref\n";
But when I run the code I get the following error:
mark
SCALAR(0x9556cf8)
Modification of a read-only value attempted at ./stringPerl.pl line 7.
How to remove the above error?
Upvotes: 1
Views: 43
Reputation: 13792
The line that causes the error is:
$$ref = "antony";
That tries to asign the value "antony" to the referenced variable by $ref, but the line:
my $ref = $nameRef + 1;
It's not a valid reference. Try to replace simply by:
my $ref = $nameRef;
So $ref
is the same as $nameRef
, which is a reference to $name
.
If you want to change a value in an array via a reference, you may write this:
my @names = ("mark");
my $nameRef = \@names;
$nameRef->[1] = "antony";
print "$names[1]\n";
print "$nameRef->[1]\n";
Upvotes: 1
Reputation: 17710
Perl string references are not C string pointers. You cannot take a reference and increment it to point somewhere else.
When you do my $ref = $nameRef + 1;
, it actually takes the SCALAR(0x9556cf8)
string and adds 1, making it a string, not a reference.
Not sure what you are trying to do exactly.
Upvotes: 2