in reply to Prototype mismatch: sub main::trim: none vs ($) at mysqlDB_serial.pl line 188.

++haukex, on everything.

It looks like you found those functions on the internet as a way to trim whitespace from strings. I searched "Left trim function to remove leading whitespace" on Google to see where it came from, and while I saw a few pages where those functions were presented as one way to do that, none had a description of the effects of the ($) prototype. While "an extra check of the parameters" may sound like a good idea, this prototype also forces scalar context on the first (and only) argument, and turns the function into an unary operator. Since prototypes are rarely used, this means that those three functions will not behave like most other subs you'll use (at least the ones from other modules). To avoid surprises, you should remove the ($) after the names trim, ltrim and rtrim.

Replies are listed 'Best First'.
Re^2: Prototype mismatch: sub main::trim: none vs ($)
by haukex (Archbishop) on Feb 08, 2017 at 14:38 UTC

    Hi Eily,

    Excellent point on bringing attention to the prototype!

    ... those three functions will not behave like most other subs you'll use (at least the ones from other modules). To avoid surprises, you should remove the ($) after the names of your subs.

    I think a trim function would make sense as a unary operator, that would put it in the same category as lc, lcfirst, uc, ucfirst, fc, length, chr, hex, oct, int, ref, scalar, and quite a few more. But this is definitely another one of those "do this only if you know what you're doing and why" cases. (Just the other day there was a thread on the same topic.)

    Regards,
    -- Hauke D

      I agree on the fact that a trim function could make sense as an unary operator. I think the problem is mostly that this was not documented, although the code seems to be meant to be shared. Personally though, I prefer only using the special case of the & prototype, where the special block syntax would be invalid without the prototype, removing the need to know how the function was declared to read a statment correctly.