Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Dynamic names

by Dwood (Acolyte)
on Nov 16, 2010 at 20:30 UTC ( [id://871823]=perlquestion: print w/replies, xml ) Need Help??

Dwood has asked for the wisdom of the Perl Monks concerning the following question:

I honestly don't see any documentation on what this feature is called so I don't know what to ask for however the best way I can think of it is the property demonstrated in the perlboot tutorial.

1. # Cow::speak, Horse::speak, Sheep::speak as before 2. @pasture = qw(Cow Cow Horse Sheep Sheep); 3. foreach $animal (@pasture) { 4. &{$animal."::speak"}; 5. }

I want to use the same principle in a parser i'm working on, creating a new (struct or hash) for every occurence of a variable declaration in my custom script utilities.

What I want it to look like is to say, have @array_vars
format of the script declarations (global <type> <name> <value>) initializing with a value being optional.

I want (dont know if I need?) a hash//struct entry in the array to be created every time there is an occurence of a global. so:

@array-><name> = TYPE => BOOLEAN, VALUE => "UNINITIALIZED"

Replies are listed 'Best First'.
Re: Dynamic names
by MidLifeXis (Monsignor) on Nov 16, 2010 at 20:47 UTC

    Try the following:

    $hash->{$name} = { TYPE => 9001, VALUE => "UNINITIALIZED", }

    BTW, this is just a hash of hashes, not necessary to be an object, so perlboot is not necessarily the best reference. Try looking for HoH in the monastery.

    --MidLifeXis

Re: Dynamic names
by cdarke (Prior) on Nov 16, 2010 at 21:17 UTC
    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(); }
    Produces:
    Moo Moo Hi, my name is Ed Baaaah Baaaah

      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.
Re: Dynamic names
by ELISHEVA (Prior) on Nov 17, 2010 at 05:16 UTC

    I'm not entirely clear on what you want to accomplish, but maybe what you meant was that you want the token type of each token to trigger certain processing? For example, if you have a name "foo" and your parser says it is a variable declaration token, you want to be able to trigger certain processing rules depending on whether that declaration is for an integer, email address, day of week, or some other special type?

    If you need to trigger special processing based solely on the combination of a name and a type, you could use a slightly modified version of cdarke 's solution:

    use strict; use warnings; package Cow; { sub speak { print ${$_[0]}, " says Moo\n" } } package Horse; { sub speak { print ${$_[0]}, " says 'Hi, my name is Ed'\n" } } package Sheep; { sub speak { print ${$_[0]}, " says Baaaah\n" } } # mapping names to types my %Pasture = ( Bessie => 'Cow', , Annie => 'Cow', , Joe => 'Horse' , Lily => 'Sheep' , James => 'Sheep' ); while (my ($name, $animal) = each(%Pasture)) { # assign a class to each name based on type my $oAnimal = bless(\do{my $anon=$name;}, $animal); # do processing that involves both name and type $oAnimal->speak(); }
      Thanks for the post!
Re: Dynamic names
by 7stud (Deacon) on Nov 16, 2010 at 21:23 UTC

    Just so you know, this code:

    &{$animal."::speak"};

    doesn't create anything. It uses what's called a "symbolic reference" to look up a subroutine that already exists. A symbolic reference is just a string, and when you try to dereference a string, {}, perl looks up the string in the symbol table, and in this case retrieves the subroutine, &, with that name.

    You can use typeglobs to create new entries in the symbol table, for instance:

    *Cow::speak = sub {print "mooo\n"}; Cow->speak(); --output:-- mooo

    The rest of your post doesn't make any sense to me.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (4)
As of 2024-03-19 03:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found