Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: On References to the Unnamed

by mstone (Deacon)
on Mar 16, 2005 at 19:48 UTC ( [id://440114]=note: print w/replies, xml ) Need Help??


in reply to On References to the Unnamed

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..

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://440114]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (7)
As of 2024-04-24 10:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found