Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re^2: Perl templating/macro creating using 'BEGIN'...

by perl-diddler (Chaplain)
on Sep 27, 2010 at 17:57 UTC ( [id://862253]=note: print w/replies, xml ) Need Help??


in reply to Re: Perl templating/macro creating using 'BEGIN'...
in thread Perl templating/macro creating using 'BEGIN'...

Also, why are you using string-eval, when the plain eval works just as well.
Because it didn't work when I tried it. Perhaps your perl works differently?
#!/usr/bin/perl -w use strict; use feature ':5.10'; package MyPackage; { BEGIN { sub package_vars { foreach(@_) { eval sub $_ { my \$p = shift; \$p->{$_} = \$_[0] if \@_; \$p->{$_}; }; } } } package_vars( qw(one two three) ); sub new { my $package=shift; my $parms=$_[0]; my $this={}; foreach(%$parms) { $this->{$_}=$parms->{$_}; } bless $this, $package; } } package main; my $p=new MyPackage({three => 3,}); $p->two(1); printf "two=%d, three=%d\n",$p->two, $p->three;
I got: Illegal declaration of anonymous subroutine at pck0.pl line 10. What do you get?

Replies are listed 'Best First'.
Re^3: Perl templating/macro creating using 'BEGIN'...
by Corion (Patriarch) on Sep 27, 2010 at 18:06 UTC

    Sorry - you don't even need "plain eval". Just assigning the anonymous subroutine to the glob is all that's needed and creates a named subroutine from the anonymous subroutine.

      Sorry - you don't even need "plain eval". Just assigning the anonymous subroutine to the glob is all that's needed and creates a named subroutine from the anonymous subroutine.
      What glob? (and what anonymous subroutine?)

        The code block following that comment:

        sub main_package_vars { foreach my $name (@_) { no strict 'refs'; *{ $name } = sub { my $p = shift; $p->{$name} = $_[0] if @_; $p->{$name}; }; } }

        This creates accessor-style subroutines with names given in @_. You can call it as

        main_package_vars( 'Some::Namespace::foo', 'main::bar', 'baz' );

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (7)
As of 2024-04-25 14:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found