in reply to What's so bad about &function(...)?

For the same reason we don't recommend writing @{\@foo} when @foo works just as well.

:-)

We're building the house of the future together.

Replies are listed 'Best First'.
Re^2: What's so bad about &function(...)?
by Zaxo (Archbishop) on Dec 07, 2005 at 19:05 UTC

    That reminds me of a question I like to use for teaching intermediate-level perlers:

    What is the difference between @{\@foo} and @{[@foo]}?
    I think it makes a good interview question, too.

    I don't think it is really the same reason at all. The reference/dereference cycle in your example is real, but insignificant, while the & sigil is usually optional but sometimes affects perl parsing and compilation. Ovid and tirwhan covered the traps nicely.

    After Compline,
    Zaxo

      I'll bite. The second makes a copy of the array, the first doesn't. Right...? I hope. Or I've embarrassed myself terribly.

        Right.

        After Compline,
        Zaxo

      What is the difference between @{\@foo} and @{@foo}?

      Um... they're both the wrong way to write @foo, but the second one's more inefficient, but caring excessively about efficiency of bad code that you should refactor anyway is a premature optimization, so ... umm... it's a trick question, with the answer of "There's no difference; you'ld never use either one in production code?"

      Do I win? :-) Or did I miss something subtle? :-(

        You're half right, but you did miss something that jdporter missed, too.

        @{\@foo} is, as far as I know, a truly useless elaboration of @foo.

        The anonymous copy provided by @{[@foo]} is sometimes useful when you want to preserve @foo's contents. Example:

        my @mutant_foo = map { mutator($_) } @{[@foo]};
        It helps with for loops, too. That kind of situation comes up surprisingly often and the copy is an effective and unobtrusive solution.

        After Compline,
        Zaxo

        @{[@foo]} is really wrong, for the obvious reason that it copies the contents of @foo into a new (anonymous) array, so that, for example, splice( @{[@foo]}, 0, 5 ) does not modify @foo.

        But why is @{\@foo} wrong? Whatever the answer is, the same could be said of &foo() (aside from the extremely tiny overhead of taking and dereffing a ref).

        We're building the house of the future together.