I have a hash in my main code that I wish to bring into a subroutine, modify and then return to print the data values.
Problem: I can't get the modified hash to return to the main code properly. When I try to print a hash value in my code I get the value from the original hash, and not the modified one. Or, I get a warning that the hash reference is undefined.
Here's an example I made of my problem using Star Trek references - I wish to replace the values in the hash (%starship) with different numbers if I find a match for the captain's name in the variable ($captains) input into the subroutine (trivia).
use strict; use warnings; my $captains = "kirkpicard"; my %starship = ( 'EntTOS'=>0, 'EntA'=>0, 'EntD'=>0, 'EntE'=>0, ); trivia ($captains,\%starship); print "Kirk was on Enterprise #: $starship{EntTOS}, $starship{EntA}\ +n"; print "Picard was on Enterprise #: $starship{EntD}, $starship{EntE}\n" +; sub trivia {, my ($captains, $starship_ref) = shift; %starship = %{$starship_ref}; if ($captains =~ m/(kirk)/) { $starship {'EntTOS'} = 1; $starship {'EntA'} = 2; } if ($captains =~ m/(picard)/) { $starship {'EntD'} = 4; $starship {'EntE'} = 5; } return %starship; }
The output I should get is as follows:
Kirk was on Enterprise #: 1, 2 Picard was on Enterprise #:4, 5
Any ideas how to make it so?
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |