in reply to Hashes and Functions

my $href = @_;

Evaluating an array as a scalar returns the number of elements in the array, so at this point $href contains '1'. You want either my($href) = @_; or my $href = shift;, or something similar that will maintain the array context you are looking for.


We're not surrounded, we're in a target-rich environment!

Replies are listed 'Best First'.
Re: Re: Hashes and Functions
by gnubbs (Beadle) on Apr 10, 2003 at 18:51 UTC

    Thanks! This was something that took me a while to get right when I was first learning perl, and now I see why. In the camel book the line is:

    my ($cref, $dref) = @_;

    For some reason, I had associated the () with the my... Now it makes perfect sense. Thanks.

    gnubbs

      Actually, in that case the parens are associated with my. You can think of my as a function just like any other function and the parens group and specify its arguments. The reason you can assign to it is because my returns a list of its newly scoped arguments, which are then assigned to like any other list assignment.

      kelan


      Perl6 Grammar Student

      IMHO, "shift" is the better way to get arguments off of @_. If you start using "shift", you'll never get confused about scalar vs. list context, etc.

      So,

      my ($cref, $dref) = @_;

      becomes

      my $cref = shift; my $dref = shift;

      Very clean, very easy. No confusion :-)

      HTH.

        Uhhh ... I disagree. It may be cleaner, but I don't think that this style will keep you learning. I believe it is better to directly confront the syntactic issues you have and learn from them than try to avoid them.

        For example, by pushing my$self into confronting list vs. scalar context, I learned more about what context really is. That allows me to take advantage of nifty features like wantarray.

        ------
        We are the carpenters and bricklayers of the Information Age.

        Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

        Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.