in reply to Function Prototypes and Array vs. List (Pt. 2)

The question is, is there a simple method to convert or expand an array into a list?
Well, yes! The simplest way possible. As simple as converting a number to a string. If you want an array to act like a list, use it in list context!

Abigail

  • Comment on Re: Function Prototypes and Array vs. List (Pt. 2)

Replies are listed 'Best First'.
Re^2: Function Prototypes and Array vs. List (Pt. 2)
by tadman (Prior) on Jun 13, 2002 at 14:42 UTC
    The problem is how adamant Perl is about backpropagating the wantarray = undef "scalar only, arrays will be converted automatically on sight" property of the function prototype. It just keeps going...and going...and going, all the way down the stack. In the example I posted, even reverse is joining the party, and it's a level removed!

    I didn't write the function that's prototyped, I just want to give data that happens to be in an array without fussing around too much, like expanding it out the hard way: $n[0],$n[1],...,$n[$#n]

    I don't disagree with your remark, I'm just astounded at how stringently prototypes are interpreted.
      But the reverse call isn't one level removed. The call to reverse is the first argument and it is being evaluated in scalar context. In your example you have only one case of using a literal list in the foo_bar() call, which gives you a prototype error. In all other cases you are calling foo_bar() with a single expression that will be evaluated according to the context of the first (or only in your case) prototype.
        We're getting extra helpings of humble pie today, that's for sure. My bad.

        In a prior version of the code, I'd put reverse in a few of the functions, for example:
        sub returns_rtwo { return reverse qw[ foo bar ]; }
        To cut down on duplication, I'd left them out.

        Here's a little snippet that takes that one step further:
        #!/usr/bin/perl -w use strict; sub foo_p($) { print "$_[0]\n" } sub foo { print "$_[0]\n" } sub baz { qw[ foo bar ] } sub zab { reverse baz() } sub bam { return (baz(),zab()) } sub bar { return bam() } foo(bar()); foo_p(bar());
        On a regular, unprotyped function, you get your regular 'foo', but a prototyped version of same is a whole different thing.

        If you've got prototyped functions, you're going to have to get serious, I suppose, and stick to the letter of the law. No extra parameters, no mis-typed values, and no "random junk".

        Update:
        Considering the normal, unmolested return value of bar() is 'foo','bar','bar','foo', it is odd that you get 'raboof' because of the forced scalar(). The last function is trying to return an array with four values, so you'd think, at least on some plane of existence, that you'd get 4 in the end, but this is not the case. The only way you get this is if you assign to a temporary array:
        sub bar { return my @foo = bam(); }