You could always use a simplified version of the trick from Glob.pm:
sub anon_ref { $N ||= 1; my $name = sprintf "var%04d", $N; my $ref = \${ 'NAMESPACE::' . $name }; delete $NAMESPACE{ $name }; $N++; return ($ref); }
It does use a name to create the variable, but then deletes that name from the symbol table, which arguably results in an anonymous scalar.
In an object constructor, it would looks like so:
sub My_object::new { my ($type, @data) = @_; $N ||= 1; my $name = sprintf "var%04d", $N; my $object = \${ 'NAMESPACE::' . $name }; delete $NAMESPACE{ $name }; $N++; bless $object, $type; $object->configure_with (@data); return ($object); }
or you can factor the ref code out into a separate function and just use:
sub My_object::new { my $O = bless anon_ref(), shift; $O->configure_with (@_); return ($O); }
By tweaking the specific kind of ref you create in anon_ref(), you can make it return scalars, lists, hashes, or entire globs. Most of the File:: classes use anonymous globs to store their filehandles, in fact..
In reply to Re: On References to the Unnamed
by mstone
in thread On References to the Unnamed
by tlm
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |