Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


What are barewords in Perl?

Arslan Tariq


A bareword is an identifier or variable without any necessary symbols or punctuation. We can say that barewords are words without quotes; that is, they are quote-less strings.


Let’s look at the example below:

my $test = helloWorld;
print "$test\n";
An example of a bareword

Although the strict rules in Perl discourage the use of ambiguous barewords, some of them are still acceptable to the parser. Now, what if we use a subroutine of the same name?

sub helloWorld
    return "Hello Educative";
$test = helloWorld;
print "$test\n";
An example of a subroutine

The subroutine is executed and it prints “Hello Educative”, which means that barewords cause ambiguity in the subroutine. Perl used “use strict” to avoid this ambiguity. The use of strict makes Perl programs less error-prone.

Bareword used in code blocks

The specially named code blocks “AUTOLOAD,” “BEGIN,” “CHECK,” “DESTROY,” “END,” “INIT,” and “UNITCHECK” are all barewords.

package Milk::Butter;
BEGIN { initialize_simians( __PACKAGE__ ) }
sub AUTOLOAD { ... }

We could separate sub from AUTOLOAD, but that’s not common.

Uses of barewords

Bareword used in package names

Package names are also barewords. Perl needs to figure out how to solve Package->method. To do this, we force the parser to treat “Package” as a package name by adding the package separator (::).

Bareword used in constants

Constants declared with the constants pragma are useful as barewords.

    use constant NAME => '';
    use constant PASSWORD => 'test@123';
return unless $name eq NAME && $pass eq PASSWORD;

The code returns false if an incorrect username and password are specified. Also, constants are not inserted into double-quoted strings.

Barewords used in hash keys

my %Pakistan = (Lahore =>'Packages Mall',
Islamabad =>'Centaurus Mall',
Gujranwala => 'Mall of Gujranwala',
Karachi => 'Atrium Mall');
my $var1 = $Pakistan{'Lahore'}; 
print($var1, "\n");
# Prints Taj Mahal
my $var2 = $Pakistan{Islamabad}; 
print($var2, "\n");
Example of a bareword

In general, hash keys in Perl are unambiguous. Here, we declare essential functions in two ways: $Pakistan{'Lahore'} and $Pakistan{Islamabad}. They both give an output, even though they are declared differently.




Arslan Tariq
Copyright ©2022 Educative, Inc. All rights reserved

View all Courses

Keep Exploring