Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
Hello! I often find myself needing to input and return multiple references from a subroutine and end up writing code that takes the following form:
my %x = ("a" => "red"); my %y = ("b" => "green"); my %z = ("c" => "black"); my ($ref1, $ref2, $ref3) = &modfifyHash(\%x, \%y, \%z); %x = %{ $ref1 }; %y = %{ $ref2 }; %z = %{ $ref3 }; sub modfifyHash { my ($ref1, $ref2, $ref3) = @_; my %x = %{ $ref1 }; my %y = %{ $ref2 }; my %z = %{ $ref3 }; $x{ "a" } = "circle"; $y{ "b" } = "square"; $z{ "c" } = "rectangle"; return(\%x, \%y, \%z) }
The, 1) create a variable to hold the reference, 2) dereference each reference, steps takes up considerable amount of space and feels like it just clutters the whole code a lot (especially when I end up doing this many times throughout a script and/or am inputing or returning many referenced variable). So I am looking for a more compact and elegant solution.... I would like to write something like:
my %x = ("a" => "red"); my %y = ("b" => "green"); my %z = ("c" => "black"); (%x, %y, %z) = %{ &modfifyHash(\%x, \%y, \%z) }; sub modfifyHash { my (%x, %y, %z) = %{ @_ }; $x{ "a" } = "circle"; $y{ "b" } = "square"; $z{ "c" } = "rectangle"; return(\%x, \%y, \%z) }
...but this does not produce the desired results, i.e. each input/returned hash in an individual variable. I also thought I might be able to use map in some clever way like:
my %x = ("a" => "red"); my %y = ("b" => "green"); my %z = ("c" => "black"); (%x, %y, %z) = map %{ $_ }, &modfifyHash(\%x, \%y, \%z); sub modfifyHash { my (%x, %y, %z) = map %{ $_ }, @_; $x{ "a" } = "circle"; $y{ "b" } = "square"; $z{ "c" } = "rectangle"; return(\%x, \%y, \%z) }
...but, again, this is not working as I would like. Could anyone share how they typically handle this in a better way?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Elegantly dereferencing multiple references
by LanX (Saint) on May 13, 2016 at 11:55 UTC | |
|
Re: Elegantly dereferencing multiple references
by Eily (Monsignor) on May 13, 2016 at 11:56 UTC | |
|
Re: Elegantly dereferencing multiple references
by haukex (Archbishop) on May 13, 2016 at 12:20 UTC | |
|
Re: Elegantly dereferencing multiple references
by Yary (Pilgrim) on May 13, 2016 at 14:47 UTC | |
|
Re: Elegantly dereferencing multiple references
by polettix (Vicar) on May 19, 2016 at 14:52 UTC | |
|
Re: Elegantly dereferencing multiple references
by LanX (Saint) on May 13, 2016 at 12:16 UTC | |
by Eily (Monsignor) on May 13, 2016 at 12:31 UTC | |
by LanX (Saint) on May 13, 2016 at 12:48 UTC | |
by LanX (Saint) on May 13, 2016 at 13:44 UTC |