[sf-perl] Make a hash key's value dependent on the key itself?

Gavin Jefferies gavin at fastperl.com
Mon Jul 3 10:55:42 PDT 2006


Hi David,

To avoid the copy error you could populate your hosts HASH
via a subroutine. This also protects you against forgetting
to do the substitution.

my $hosts = {};

sub mkhosts {
    my $hostname = shift;
    my $parms    = shift;

    die "no rsync_target specified for $hostname" unless
$parms->{ rsync_target };

    $parms->{ rsync_target } =~
s#::SOURCEHOST::#$hostname#;

    $hosts->{ $hostname } = $parms;
}

mkhosts(foo => {
          source_tree  => '/some/dir',
          rsync_target => "bat:$spool_dir/::SOURCEHOST::/",
      });

mkhosts(bar => {
          source_tree  => '/some/other/dir',
          rsync_target => "bat:$spool_dir/::SOURCEHOST::/",
      });

mkhosts(bat => {
          source_tree => '/yet/another/dir',
          rsync_target =>
"mumble:$raid_root/::SOURCEHOST::/",
      });

HTH,
Gavin


--- David Alban <extasia at extasia.org> wrote:

> On 7/1/06, Michael Budash <mbudash at sonic.net> wrote:
> > you might want to explain why you can't simply handle
> this in the
> > code that makes use of this data.
> 
> Yeah, that's what i finally did. :-)
> 
> The more I thought about it, the more I became convinced
> that if there
> was a way to do this, it would probably be unnecessarily
> complicated.
> So I did:
> 
> $hosts => {
>     foo => {
>         source_tree  => '/some/dir',
>         rsync_target => "bat:$spool_dir/::SOURCEHOST::/",
>     },
>     bar => {
>         source_tree  => '/some/other/dir',
>         rsync_target => "bat:$spool_dir/::SOURCEHOST::/",
>     },
>     bat => {
>         source_tree => '/yet/another/dir',
>         rsync_target =>
> "mumble:$raid_root/::SOURCEHOST::/",
>     },
>     .
>     .
>     .
> };
> 
> Then no matter which machine I'm on, I can do:
> 
>   $rsync_target
>       = $hosts->{ $hostname }{ rsync_target } =~
> s#::SOURCEHOST::#$hostname#;
> 
> What I *really* wanted was to be avoid copy errors if I
> added a new
> host in the future.  That is, in the editor, copy and
> paste the foo
> data, rename the foo key with, say, baz, but then forget
> to change foo
> wherever it appears in the values of the new baz hash.
> 
> Thanks.
> 
> -- 
> Live in a world of your own, but always welcome visitors.
> _______________________________________________
> SanFrancisco-pm mailing list
> SanFrancisco-pm at pm.org
> http://mail.pm.org/mailman/listinfo/sanfrancisco-pm
> 





More information about the SanFrancisco-pm mailing list