Barewords in Perl

use strict has 3 parts. One of them, also called use strict "subs" disables the inappropriate use of barewords.

What does that mean?

Without this restriction code like this would work and print "hello".


  my $x = hello;
  print "$x\n";    # hello

That's strange in itself as we are used to put strings in quotes but Perl allows "barewords" - words without quotes - to behave like strings.

So the above code would print "hello".

Well, at least until someone added a subroutine called "hello" to the top of your script:


  sub hello {
    return "zzz";
  }

  my $x = hello;
  print "$x\n";    # zzz

Yes. In this version perl sees the hello() subroutine, calls it and assigns its return value to $x.

Then if someone moves the subroutine to the end of your file, after the assignment, perl suddenly does not see the subroution at the time of the assignment so we are back, having "hello" in $x.

No, you don't want to get in such a mess by accident. Or probably ever. Having use strict in your code perl will not allow that bareword "hello" in your code, avoiding this type of confusion.


  use strict;

  my $x = hello;
  print "$x\n";

Gives the following error:


  Bareword "hello" not allowed while "strict subs" in use at script.pl line 3.
  Execution of script.pl aborted due to compilation errors.

Good uses of barewords

There are other places where barewords can be used even when use strict "subs" is in effect.

First of all the names of the subroutines we create are really just barewords. That's good to keep.

Also when we are refering to an element of a hash we can use barewords within the curly braces and words on the left hand side of the fat arrow => can also be left without quotes:


  use strict;
  use warnings;
  use 5.010;
  
  my %h = ( name => 'Foo' );
  
  say $h{name};
  

In both cases in the above code "name" is a bareword but these are allowed even when use strict is in effect.


Perl tutorial and video course

For further articles see the Beginner Perl Maven tutorial book and video course.


In the comments, please wrap your code snippets within <pre> </pre> tags and use spaces for indentation.
blog comments powered by Disqus
Online courses:


Would you like to get
updated when I publish
the next article?

Follow me:

Google Plus Twitter RSS feed