J Krugman said:
[...]
I see no reason this won't work:
I like this one a lot. And also Anno's
bless \ "$_", 'Foo' for 3;
but I'm mystified by both. Specifically, I don't understand why
the following:
bless \undef, 'Foo' ===> Modification of a read-only value attempted
bless \\undef, 'Foo' ===> [ no error ]
bless \1, 'Foo' ===> Modification of a read-only value attempted
bless \\1, 'Foo' ===> Modification of a read-only value attempted
Why are the behaviors for undef and 1 different?
I think it shouldn't work in the case of undef either. A spelled-out
reference is basically a memory address. It depends on whatever the
reference is taken of and cannot be changed.
I can only guess at why Anno's idea works. It looks like interpolation
causes a new memory location to be created. But I have never seen
anything like this documented anywhere, so I'm just guessing wildly.
So am I, I must confess. I don't know if it is documented anywhere.
I have used it (in variants) for so long, it doesn't bother me anymore.
In a similar way
for ( qw( fie foe fum) ) {
$_ .= 'X';
}
doesn't work, but
for ( map "$_", qw( fie foe fum) ) {
$_ .= 'X';
}
does.
I added "my" solution
bless \ "$_", 'Foo' for 3;
in the spirit of TIMTOWTDI, but it has disadvantages. For one, it doesn't
return a value ("for" doesn't), so if you need the value (you will) it must
be assigned inside the for "loop". Then you can't declare the variable
right there (not in a modified statement), so it becomes
my $obj;
$obj = bless \ "$_", 'Foo' for 3;
If it's the last thing happening in a sub,
return bless \ "$_", 'Foo' for 3;
is okay, but return is necessary. In general I'd go with
my $obj = bless \ do { my $x }, 'Foo';
The do {} block is optional, but with it you strictly have an anonymous
scalar ref.
Anno