Every now and again, I want to set the value of a number of properties on an object from a hash, where the method name is the same as the key name, but with a prefix, eg
$object->set_date( $hash{ date } );
But how to do this for all the keys in a hash? I've thought of two methods:
Method 1:
---------
for ( keys %hash ) {
my $method = "set_$_";
$object->$method( $hash{ $_ } );
}
Method 2:
---------
for ( keys %hash ) {
$object->${ \"set_$_" }( $hash{ $_ } );
}
I prefer the second method, because it is shorter, but (1) it is less readable and (2) Perl::Tidy reformats it with a space before the arrow, which still works, but looks rather odd:
$object ->${ \"set_$_" }( $hash{$_} );
Which method would you prefer? One of the above, or some other syntax?
(Note: I benchmarked the difference between these two, and while the temp var is slightly faster, the difference is negligible.)
#!/usr/bin/perl
use strict;
use warnings;
use Benchmark qw(cmpthese);
package foo;
{
sub set_var1 { }
sub set_var2 { }
sub set_var3 { }
sub set_var4 { }
sub set_var5 { }
}
package main;
my $object = bless {}, 'foo';
my %hash = map { ( "var$_" => $_ ) } ( 1 .. 5 );
sub temp_var {
for ( keys %hash ) {
my $method = "set_$_";
$object->$method( $hash{$_} );
}
}
sub deref {
for ( keys %hash ) {
$object ->${ \"set_$_" }( $hash{$_} );
}
}
cmpthese( 1_000_000,
{ temp_var => \&temp_var,
deref => \&deref
}
);
Results:
Rate deref temp_var
deref 176991/s -- -18%
temp_var 215054/s 22% --
Update: corrected a typo in Method 2, thanks to zwon for pointing it out
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, 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, 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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.