Skip to content
Related Articles

Related Articles

Improve Article

Barewords in Perl

  • Last Updated : 21 Nov, 2019

Like any other language, Perl is also error-prone. some of the features in Perl are very difficult to use correctly. Perl’s parser understands Perl’s operators, functions, methods with the help of some symbols. But this is not the case always. The parser has to do the guesswork when we use Barewords. Bareword is an identifier or variable without the necessary symbols or punctuations. Putting this simply, we can say that Barewords are words without quotes(i.e Quotless Strings). Even though the strict rules in Perl discourages the use of ambiguous barewords, some of them are still acceptable to the parser.

my $bw = BWeg;
print "$bw\n";

This will print BWeg. But what about the case when we use a subroutine of the same name?

sub BWeg
    return "Subroutine has been executed";
$bw = BWeg;
print "$bw\n";

Here we can see that the subroutine has been executed. So we can also say that Barewords causes ambiguity. In order to avoid this ambiguity, Perl has “use strict”. Use strict is used to make Perl programs less error-prone.

use strict;
my $bw = BWeg;
print "$bw\n";

It issues a compilation error like this.

How to use barewords correctly?

Barewords can be used in Hash keys, package names, constants, named code blocks.

my %India = (UP =>'Taj Mahal',
Rajastan =>'Chittorgarh'
Kerala =>'Bakel Fort');
# Prints Bakel Fort
my $var1 = $India{'Kerala'}; 
print($var1, "\n");
# Prints Taj Mahal
my $var2 = $India{UP}; 
print($var2, "\n");

Usually hash keys in Perl are unambiguous. Here we can see that we declared key functions in 2 ways as $India{‘Kerala’} and $India{UP}. Eventhough they are declared differently they will give outputs.

Bareword package names

Package names are also bare words. Perl must identify how to parse Package->method. For that we force the parser to treat Package as a package name by appending the package separator (::).

Bareword named code blocks

The special named code blocks AUTOLOAD, BEGIN, CHECK, DESTROY, END, INIT, and UNITCHECK are barewords.

package Monkey::Butler;
BEGIN { initialize_simians( __PACKAGE__ ) }
sub AUTOLOAD { ... }

we can separate sub from AUTOLOAD, but it is not a common practice.

Bareword constants

Constants declared with the constant pragma are usable as barewords.

# don't use this for real authentication
    use constant NAME => 'GeeksForGeeks';
    use constant PASSWORD => 'GeeksPl@tform';
return unless $name eq NAME && $pass eq PASSWORD;

It returns false if the wrong username and password are given. Also, constants do not interpolate in double-quoted strings.

My Personal Notes arrow_drop_up
Recommended Articles
Page :