There are two solutions to your problem.

The first will work, has already been suggested, but isn't going to give you much mileage past this particular case. That is, to shift the scalar out of @_ before assigning the remaining contents of @_ to your hash.

But the proper way to pass more than one complex variable (such as an array or a hash) into a subroutine is to pass a reference to the actual entity, rather than the entity itself. That is done like this:

my %new_stuff = ( "RATING" => 4.99 ); db_modify_account( "jdonald", \%new_stuff ); sub db_modify_account { my( $uid, $ref_new_data ) = @_; while ( ( $key, $value ) = each %{ $ref_new_data } ) { print "The $key is: $value.<br />"; } print "Oh, and the user is $uid.<br />"; }

The thing to keep in mind is that all arguments passed to a sub get flattened out into a single list. Also remember that a hash, in list context, becomes a flat list of key, value, key, value, etc.

So your current implementation passes the following list to the sub: "jdonald", "RATING", 4.99. And when the hash is reconstructed, under your current implementation, it is mapped out like this: jdonald => RATING, 4.99 => undef

Passing the references allows you to avoid the trickery it would take to figure out how to rebuild the complex data into a hash, array, or whatever. Imagine trying to pass two hashes, or two arrays as flat lists, and figuring out where one ends and the next begins. Passing references is a whole lot easier.

This is discussed in a bit more detail in perlsub, perlref, and perlreftut.


Dave


In reply to Re: Passing a hash, and a scalar to subroutine by davido
in thread Passing a hash, and a scalar to subroutine by gorillaman

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.