I've been trying to learn Perl for a few days, and am still frequently surprised and sometimes mystified at how and why it does things. Here is my latest puzzle: why are the following two blocks of code not equivalent?
my $thing = '';
bless \$thing; # class is implicit
versus
my $thing = \'';
bless $thing; # class again implicit
The second form says "Modification of a read-only value attempted" on the second line.
\'' is a reference to a literal.
\$thing is a reference to $thing. The value of $thing is set to the empty string at the moment.
The reason for the error you are getting is the same as the reason the following will give you the same error:
my $thing = \5;
$$thing = 10;
bless modifies the thing to which its first argument refers. In this case, and in yours, $x refers to something that is not modifiable.
See perldoc perlobj:
Objects Are Blessed; Variables Are Not
When we
blesssomething, we are not blessing the variable which contains a reference to that thing, nor are we blessing the reference that the variable stores; we are blessing the thing that the variable refers to (sometimes known as the referent). (emphasis mine)
If you want a class backed by a scalar, you can do this:
#!/usr/bin/env perl
use v5.10;
package MyString;
use strict; use warnings;
sub new {
my ($class, $self) = @_;
bless \$self => $class;
}
sub content { ${$_[0] }
sub length { length ${$_[0]} }
package main;
use strict; use warnings;
my $string => MyString->new("Hello World");
say $string->$_ for qw(content length);
Of course, you need to exercise discipline and not modify instance data through the backdoor as in $$string = "Bye bye cruel world".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With