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?


In reply to Replacing original hash with modified hash returned from subroutine by CommaSplice

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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, details, 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, summary, 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.