One of the existing packages Anonymous Monk recommended is probably the way to go for any production code. However, if this is a learning exercise, you might start with something like the following:
#!/usr/bin/env perl use 5.010; use warnings; my $suf = 42; my $my_string = Sillystring->new('Prefix_', \$suf); say $my_string; $suf = 31; say $my_string; package Sillystring; use Carp; use overload '""' => sub { my $self = shift; $self->{prefix} . ${$self->{suffix +}} }; sub new { my ($class, $prefix, $suffix) = @_; croak "Suffix must be a SCALAR ref" unless ref($suffix) eq 'SCALAR +'; bless { prefix => $prefix, suffix => $suffix, }, $class; } 1;
This will do what you want, although it's pretty terrible OO design, and not all string operations are supported. Concatenation, for instance, will actually replace the object with an unblessed ordinary string. This could be avoided by overloading the concatenation operator.
If efficiency is a concern, realize that any such implementation is going to be far slower than ordinary scalars, but there's not much you can do about that except benchmark.
In reply to Re: if $a = 'some' . $b, and $b then changes, how to make $a change too? See inside.
by rjt
in thread if $a = 'some' . $b, and $b then changes, how to make $a change too? See inside.
by Doctrin
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |