Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

Re: Dynamic names

by cdarke (Prior)
on Nov 16, 2010 at 21:17 UTC ( #871835=note: print w/replies, xml ) Need Help??

in reply to Dynamic names

You have a classic example of polymorphism. TMTOWTDI, here is one. In the loop we change the names of the animals to be blessed references of the relevant class. The trick here is that the second argument to bless is the class name, which can be a text string (otherwise we are into nasty evals).
use warnings; use strict; package Cow; { sub speak { print "Moo\n" } } package Horse; { sub speak { print "Hi, my name is Ed\n" } } package Sheep; { sub speak { print "Baaaah\n" } } my @pasture = qw(Cow Cow Horse Sheep Sheep); foreach my $animal (@pasture) { $animal = (bless \do{my $anon}, $animal); $animal->speak(); }
Moo Moo Hi, my name is Ed Baaaah Baaaah

Replies are listed 'Best First'.
Re^2: Dynamic names
by 7stud (Deacon) on Nov 16, 2010 at 21:31 UTC

    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(); }
      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;

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://871835]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (3)
As of 2018-02-20 22:17 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (274 votes). Check out past polls.