Why can't I omit () here?

SaveImages @img_sources; 

The above message states:

 Array found where operator expected 

Why can't I omit () here?

+6
source share
5 answers

because after the call, your SaveImages routine is declared. Brackets are not needed if a subroutine is declared before the call.

example:

 use strict; use warnings; use Data::Dumper; my @ar = (1, 2); fn @ar; sub fn { print Dumper \@_; } 

not working as well

 use strict; use warnings; use Data::Dumper; my @ar = (1, 2); sub fn { print Dumper \@_; } fn @ar; 

works.

This is the expected behavior and is indicated in the book of camels.

+13
source

Perl can parse subroutine calls without parsers if they were previously declared (or defined). For instance:

 sub SaveImages; SaveImages @img_sources; 
+6
source

From perlsub :

To call routines:

 NAME(LIST); # & is optional with parentheses. NAME LIST; # Parentheses optional if predeclared/imported. &NAME(LIST); # Circumvent prototypes. &NAME; # Makes current @_ visible to called subroutine. 

Usually submarines are not declared in practice. This is usually not a problem, as people are usually used to using parsers with subs created by the programmer.

Perl :: Critic (A module that supports Damien Conway's Perltopia model, as outlined in Perl Best Practices) offers the following treatments for subtitles:

  • Ban ampersands and sigils.
  • Prohibit prototype routines.
  • Disable parsers with built-in modules.

One of the reasons for not using partners with built-in modules is to make them visually different from the software functions that parsers traditionally use. Since this is unusual for pre-sale subnets, and it is not recommended to use an ampersand (because it changes the way @_ is processed) or prototypes (because, well, it's a long story), this leaves a very strong background for using partners with script -defined subs.

+6
source

Many good points here, one more: see also subs pragma . Used as use subs qw/SaveImage/; before calling the function (probably near the top with other use calls), this should nicely predict your sub in a less intrusive way.

+4
source

You can omit () with built-in functions (see perlfunc ), because built-in functions are keywords of the language and do not need brackets that must be recognized as functions.

Some imported functions (like max from List::Util ), usually from the main modules, can also be called without parentheses.

If a subroutine is declared before a call, the brackets can also be omitted, although Perl Best Practices (Chapter 2, Section 4) recommends avoiding it to distinguish between subroutine calls and built-in modules.

-2
source

Source: https://habr.com/ru/post/891615/


All Articles