Use of colon in method and function calls in Perl 6
One of the main reasons to use a colon instead of parens is that it can help declutter your code, by removing one set of parens. Otherwise they are exactly the same.
When you have print: @a
, what you are really doing is putting a label on the line, and letting the @a
fall-through. Which in the REPL will call say
with the value.
If you don't use parens or a colon on a method call, then the method would get called with no arguments.
You can swap the order of the method, and the invocant if you use a colon.
say $*ERR: 'hello world'; # $*ERR.say('hello world')
Just to clarify a little further - using the colon instead of parentheses is an alternative method calling syntax, not an alternative function calling syntax. It's very handy when passing a function or block as an argument to a method. Using grep or map are common examples - consider;
@measurements.map( { check_accuracy($_); fail "bad value" if $_ < 0 } );
Notice I've put an extra space after the closing curly to try and separate the function I'm passing from the necessary syntax required to close off the method call. The reader of this code fully understands the whole block is an argument of the call and is usually focussed on what the contents of the block is going to achieve - and then comes across what I call the "Lone Paren" - and like the Lone Ranger is always seen with his trusty steed, Silver, the Lone Paren is nearly always next to his trusty steed, Semicolon.
Why not junk them both?
The alternative method call syntax combined with the semicolon being optional if a statement finishes with a closing curly, makes that possible;
@measurements.map: { check_accuracy($_); fail "bad value" if $_ < 0 }
Much better.
While the alternative method call format is another bit of syntax to learn, it's easily understood and in some circumstances, like above, makes the resultant code cleaner and easier to read.