Hi Anonymous,

send_1 is a good example of passing named parameters to a sub with a hash. (Update: Technically, what is happening is that the subroutine is passed a flat list of key+value pairs, since using the => operator doesn't automatically make something a hash. However, once you say my (%args) = @_;, that flat list of key+value pairs is stored in a hash.)

However, in send_2, in the call of the sub (send_2( { name => ... } )) what you are passing the sub is a reference to an anonymous hash, whereas the implementation of sub send_2 is expecting a flat list of positional parameters. The correct way to call the sub send_2 in your example code would be:

send_2( $name, $pic, 'test' );

If instead you wanted to implement arguments passed in as a hash reference, you'd need to rewrite sub send_2 like this (untested):

sub send_2 { my ($args) = @_; my $name = $args->{ name } || ''; my $filehandle = $args->{ filehandle } || ''; my $id = $args->{ id } || ''; }

Update: See "Use Rule 2" in perlreftut for an explanation of the $args->{...} syntax. Note that it could also be written $$args{...}.

Hope this helps,
-- Hauke D


In reply to Re: More efficient ways to pass values to a sub routine by haukex
in thread More efficient ways to pass values to a sub routine by Anonymous Monk

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.