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. Example:
Perl
#!usr/bin/perl
my $bw = BWeg;
print " $bw \n";
|
This will print BWeg. But what about the case when we use a subroutine of the same name? Example:
Perl
#!usr/bin/perl
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. Example:
Perl
#!usr/bin/perl
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. Example:
Perl
#!usr/bin/perl
my %India = ( UP => 'Taj Mahal' ,
Rajasthan => 'Chittorgarh' ,
Kerala => 'Bakel Fort' );
my $var1 = $India { 'Kerala' };
print ( $var1 , "\n");
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.
perl
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.
perl
use constant NAME => 'GeeksForGeeks' ;
use constant PASSWORD => 'GeeksPl@tform' ;
$name =;
$pass =;
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.
Last Updated :
25 Aug, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...