BrowserUk has asked for the wisdom of the Perl Monks concerning the following question:
I swear I've had this work before, but not today. I have a GLOBREF held in a lexical scalar. I can assign new values to the GLOBs SCALAR, ARRAY & HASH slots, independantly of each other just fine.
Now I need to add or modify the CODE slot, without affecting the existing values in the other slots. I've tried various syntaxes, including some stupid ones, but nothing work?
#! perl -slw use strict; no warnings 'uninitialized'; ## supress expected warnings ## Place a globref into a lexical scalar my $glob = \ do{ local *GLOB; }; print "\$glob = ", $glob; print "$_ => ", *$glob{ $_ }, ' => ', $_ eq 'SCALAR' ? ${ *$glob } : $_ eq 'ARRAY' ? join ', ', @{ *$glob } : $_ eq 'HASH' ? join ', ', %{ *$glob } : # $_ eq 'CODE' ? &{ *$glob } : ## fatal as CODE slot i +s empty 'n/a' for qw[ SCALAR ARRAY HASH CODE IO FORMAT ]; print "The scalar slot is initialised to point to undef(?) '${ *$glob +}'"; print "\n-------\n\n Now assign some values to the slots\n"; ${ *$glob } = 'A scalar'; @{ *$glob } = qw[ an array ]; %{ *$glob } = qw[ This is a hash ]; print $glob; print "$_ => ", *$glob{ $_ }, ' => ', $_ eq 'SCALAR' ? ${ *$glob } : $_ eq 'ARRAY' ? join ', ', @{ *$glob } : $_ eq 'HASH' ? join ', ', %{ *$glob } : # $_ eq 'CODE' ? &{ *$glob } : 'n/a' for qw[ SCALAR ARRAY HASH CODE IO FORMAT ]; ## HOW TO ASSIGN A VALUE TO THE CODEREF (not overwriting all the other + slots!) ## This attempts to invoke the sub # &{ *$glob } = sub{ print 'Anon 1'; }; ## This fails - $glob becomes a REF(0x....) # *{ *$glob } = sub{ print 'Anon'; }; # print "\n\nAfter \*{ *\$glob } = sub{ ... }: ", $glob; # >> After *{ *$glob } = sub{ ... }: REF(0x224fe4) ## This fails in the same way # *$glob = sub{ print 'Anon'; }; # print "\n\nAfter *\$glob = sub{ ... }: ", $glob; # >> After *$glob = sub{ ... }: REF(0x224fe4) ## And so does this. # *{ $glob } = sub{ print 'Anon'; }; # print "\n\nAfter \*{ \$glob } = sub{ ... }: ", $glob; # >> After *$glob = sub{ ... }: REF(0x224fe4) ## This (unsurprisingly) just assigns a normal coderef. # $glob = sub{ print 'Anon 2'; }; # print "\n\nAfter \$glob = sub{ ... }: ", $glob; # >> After $glob = sub{ ... }: CODE(0x18623a4) print "$_ => ", *$glob{ $_ }, ' => ', $_ eq 'SCALAR' ? ${ *$glob } : $_ eq 'ARRAY' ? join ', ', @{ *$glob } : $_ eq 'HASH' ? join ', ', %{ *$glob } : $_ eq 'CODE' ? &{ *$glob } : 'n/a' for qw[ SCALAR ARRAY HASH CODE IO FORMAT ];
|
|---|