CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Intermediate:
Dynamically defined methods and use strict

 



rpaskudniak
User


Oct 11, 2010, 9:39 PM

Post #1 of 1 (496 views)
Dynamically defined methods and use strict Can't Post

Hi family, after an absence to regroup..

The class I was working on last time is successful but limited. Also, not CPAN-worthy. In the process of working on that, I have written a couple of methods, named identically to the attributes on which they operate. They are:
- $object->in_delim()
- $object->out_delim()

In each case, if the user supplied a parameter, the method sets the attribute to that value. In either case, it returns the value in there. Hence, this would be called an accessor-mutator. At least that's what Sam Tregar calls it in his excellent book Writing Perl Modules for CPAN (2002 edition). Since the code is identical for both methods, except for the name of the attribute and its method, I mimicked code from page 86 of that book, placed right after the package definition:


Code
package UNLreport; 
..
my @attrs = qw(in_delim out_delim); # Create methods named like attribs
for my $attr (@attrs)
{
*$attr = sub {
my $self = shift(@_);
# Use only first character of string
$self->{$attr} = substr((shift(@_)), 0, 1) if (@_);
# If specified b, it means blank
$self->{$attr} = ' ' if ($self->{$attr} == 'b');
return $self->{$attr};
}
}

In this way, before any objects are created, I have created these subroutines by creating their references in the symbol table.

The technique looked sooo cool! Cool Until I tried it. Right at the "use" statement in the application, I got this error:


Quote
$ ./beautify-unl.pl xyz
Can't use string ("in_delim") as a symbol ref while "strict refs" in use at UNLreport.pm line 61.

Line 61 is the first line of code (the new() method) following the close-braces of the above loop.

Hey, I want to "use strict". Is there something I can do to be able to use this technique under the "use strict" stricture? I tries prototyping them but my efforts were ignored. Frown

Should I be posting this question in the "advanced" forum?

Thanks for tips here.
--------------------
-- Rasputin Paskudniak (In perpetual pursuit of undomesticated, semi-aquatic avians)

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives