Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re^2: Dynamic names

by 7stud (Deacon)
on Nov 16, 2010 at 21:31 UTC ( #871841=note: print w/ replies, xml ) Need Help??


in reply to Re: Dynamic names
in thread Dynamic names

1) What does do{my $anon} accomplish?

2) What does your code accomplish that this doesn't:

my @pasture = qw(Cow Cow Horse Sheep Sheep); for my $beast (@pasture) { $beast->speak(); }


Comment on Re^2: Dynamic names
Download Code
Re^3: Dynamic names
by cdarke (Prior) on Nov 16, 2010 at 21:41 UTC
    The \do{my $anon} creates an anonymous reference which can be blessed. To be honest it doesn't do anything more than your simpler example in this case.

    Update: To clarify. Just using the plain text string is a class call - the first argument passed to each subroutine will be the name of the class (Cow, Horse, Sheep). My version, which creates a reference to an anonymous scalar, is an object call - the first argument passed to each argument is a unique reference referring to each animal, rather than each species. So this enables other magic to be performed because we can identify not just the type of animal (the class) the which Cow or Sheep, if we need to. It is also the basis of inside-out objects. I'm not clear if the questioner needs this extra level of control though.

      Hi, I have another question about that do{} construct. Is there any reason to use a do construct and not:

      bless \my $anon, $class;

      or the even easier to type:

      bless {}, $class;
        The first bless \my $anon, $class; retains the name $anon for the rest of the code block - it is no longer anonymous.

        The second bless {}, $class; constructs an anonymous hash, which I believe uses more memory. I cannot claim I invented the use of the do{ } construct in this way, I stole it from TheDamian.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (7)
As of 2014-12-20 01:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (95 votes), past polls