in reply to passing subroutine arguments directly into a hash
One thing is that you can pass a reference to a hash instead and then simply replace
withmy ($host)=@_; $host="foo";
Another issue I've found when passing user generated hashes, or hashrefs, as parameters is that its easy to make errors. Just misspell a key name and you've got an error, sometimes one that is hard to track down. So ive found its worth the time to add code to trap incorrect keys. This is nice because similar to drewbies and IraTarballs code it provides defaults as well. Which I find usefull in a constructor, one place where you tend to get named parameter calling conventions.my $hash=shift; $hash->{host}="foo";
It might be a bit long but the point was to show that with perl you have a lot of flexibility in how you can call a subroutine but that it leaves all the errorchecking to you.package Foo; use strict; use Carp; use Data::Dumper; my %defaults=( a => "sn",b=>"afu" ); sub test{shift; print "test:",shift,"\n"} sub test2{&test}; sub new { my $class = shift; my $attrs = shift; my %params = @_; my $self=bless {%defaults},$class; for my $param (keys %params) { croak "Unknown param $param" unless exists($self->{$param}); $self->{$param}=$params{$param}; } for my $attr (keys %$attrs) { croak "Unknown attribute" unless $self->can($attr); $self->$attr($attrs->{$attr}); } return $self; } my $t=Foo->new( { test=>"Hello", test2=>"There", },a=>1,b=>2); my $tt=Foo->new(); print Dumper $t,$tt;
Yves
--
You are not ready to use symrefs unless you already know why they are bad. -- tadmc (CLPM)
|
---|
Replies are listed 'Best First'. | |
---|---|
Re (tilly) 2: passing subroutine arguments directly into a hash
by tilly (Archbishop) on Oct 20, 2001 at 19:31 UTC | |
by demerphq (Chancellor) on Oct 21, 2001 at 04:47 UTC | |
by tilly (Archbishop) on Oct 21, 2001 at 05:29 UTC | |
by demerphq (Chancellor) on Oct 21, 2001 at 15:45 UTC | |
by tilly (Archbishop) on Oct 21, 2001 at 18:58 UTC | |
by Hofmator (Curate) on Oct 22, 2001 at 14:31 UTC |
In Section
Seekers of Perl Wisdom