I feel like this is a very simple question, but I can't seem to find the answer.

I'm trying to create a new class. Most of my accessors are dynamically generated with AUTOLOAD, but I have a few that need to verify data instead of blindly accepting it. Take this code as example:

sub new { my $class = shift; my %args = @_; my %hash = ( _foo => 0, _bar => 0, _baz => 0, ); my $self = bless( \%hash, $class ); ... return $self; } sub AUTOLOAD { # do stuff to auto-generate accessors for anything in my %hash + (except without preceding underscore), so "foo" and "bar" } sub baz { # actually verify input data here }

Now, where my "..." is in the new method, I was doing something like this:

foreach ( keys %args ) { if( exists $hash{ '_' . $_ } ) { $self->{ $_ } = $args{ $_ }; } }

So if I called my new as This::Object->new( bar=>7, baz=>9 );, this would just put each value into my object. But, obviously, I want to actually verify this data, so what I really want to do is call the appropriate accessor method, but I can't seem to figure out how. So, in this example, the 'new' method would do something like call $self->bar( 7 ) and $self->baz( 9 )

Can somebody please point me to the appropriate documentation for this? It almost certainly has to be very common-place in class creation. Thanks in advance for the help!

    -Bryan


In reply to Calling arbitrary method from new by mrborisguy

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.