tfoertsch has asked for the wisdom of the Perl Monks concerning the following question:

What ist wrong with this statement?
$ echo huhu | perl -Mstrict -e '(sub {sysread @_})->(\*STDIN, my $buf, + 100)' Not enough arguments for sysread at -e line 1, near "@l}" Execution of -e aborted due to compilation errors.
Why do I have to write it the long way?
$ echo huhu | perl -Mstrict -e '(sub {sysread $_[0], $_[1], $_[2], (@_ +>3?$_[3]:())})->(\*STDIN, my $buf, 100); print $buf' huhu
Thanks,
Torsten

Replies are listed 'Best First'.
Re: What is wrong with "sysread @list"
by jwkrahn (Abbot) on Sep 10, 2008 at 14:54 UTC

    Because sysread takes four scalars as arguments, not a list, so @_ is used in scalar context:

    $ perl -le'print prototype "CORE::sysread"' *\$$;$
Re: What is wrong with "sysread @list"
by tilly (Archbishop) on Sep 10, 2008 at 18:04 UTC
    jwkrahn already gave the right answer, but I suspect you might not understand it.

    A lot of Perl built-ins, and a few user defined functions, have "prototypes". What prototypes do is change Perl's usual argument list rules. We take some of these for granted:

    push @foo, $this, $that;
    If you think about it, push can't be getting the normal argument list, because if it was then it would get a list of everything to go into @foo, but wouldn't know about @foo. Instead it has a prototype that gives it a reference to @foo, and then the elements to add to it.

    Anyways there are many different possible prototypes. You can, as with push, convert an array into a reference to an array. Or, as with each, a hash into a reference to a hash. Or you can, as sysread does, convert arguments into scalars. Which means that if you pass it an array, it will coerce the array into a scalar saying the length of the array.

    So should you use them? In general, no. As you discovered, prototypes violate the principle of not surprising people. Some uses, such as push, get amortized over so many uses that people just take them for granted. But unless you're using a function that often, you don't want to use prototypes.

    Unfortunately we can't ever change existing prototypes on the lesser used built-ins because there is code that depends on them. And, as with sysread, they will cause surprise from time to time.

Re: What is wrong with "sysread @list"
by ikegami (Patriarch) on Sep 10, 2008 at 23:46 UTC
    Without the prototype,
    >perl -c -e"use strict; use warnings; sysread(FH, my $buf='', 16384)" Name "main::FH" used only once: possible typo at -e line 1. -e syntax OK >perl -c -e"use strict; use warnings; foo(FH, my $buf='', 16384)" Bareword "FH" not allowed while "strict subs" in use at -e line 1. -e had compilation errors.