If you want to use named parameters, I suggest you use a named parameter parser. I have attached my version of the named (switched ) paramter parser as well as my version of the shapes module.
package NP;
require 5.00503;
require Exporter;
use strict;
use warnings;
use Carp;
use Data::Dumper;
use vars qw/ @ISA @EXPORT /;
@ISA = qw/ Exporter /;
@EXPORT = qw/ ParseNamedParameters /;
sub ParseNamedParameters
{
my $allowed_parameters = shift;
my @param = split /\|/, $allowed_parameters;
my %param = ();
return undef unless scalar @_; # must have something to decode fir
+st
if (ref $_[0] eq 'HASH') {
# Parameters passed in as HASHREF
for my $p (keys %{$_[1]}) {
if ($p !~ /^(?:$allowed_parameters)$/i) {
print "Unknown parameter '$p', must be [$allowed_param
+eters]\n";
} else {
$param{'_' . lc $p} = $_[1]->{$p};
}
}
} elsif ($_[0] =~ /^-(?=$allowed_parameters)/i) {
# Parameters passed in as named parameters
my (%p) = @_;
for my $p (keys %p) {
if ($p !~ /^-(?:$allowed_parameters)$/i) {
print "Unknown parameter '$p', must be [$allowed_param
+eters]\n"
} else {
$param{'_' . lc substr($p,1)} = $p{$p};
}
}
} else {
for my $p (@param) {
my $val = shift;
$param{'_' . lc $p} = $val;
}
}
return \%param;
}
1;
package shapes;
use NP;
sub new {
my $class = shift || "shapes";
my $self = {};
bless $self, $class;
my $allowed_parameters = "shape";
# only decode parameters for the base object
# derived objects have to decode their own parameters
if ($class eq "shapes") {
my $param = ParseNamedParameters($allowed_parameters, @_);
@{$self}{keys %$param} = values %$param;
}
return $self;
}
sub print_shape {
my $self = shift;
print $self->{_shape}{line1} . "\n";
print $self->{_shape}{line2} . "\n";
print $self->{_shape}{line3} . "\n";
}
1;
#!/usr/bin/perl -w
use strict;
use lib "./";
use shapes;
my %box;
$box{line1} = ' ---';
$box{line2} = '| |';
$box{line3} = ' ---';
my $box = shapes->new(-shape => \%box);
$box->print_shape();
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|