forked from szabgab/perlmaven.com
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbarewords-in-perl.tt
More file actions
94 lines (66 loc) · 2.24 KB
/
barewords-in-perl.tt
File metadata and controls
94 lines (66 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
=title Barewords in Perl
=timestamp 2013-01-15T10:45:56
=indexes bareword, strict
=status show
=books beginner_book
=author szabgab
=index 1
=archive 1
=feed 1
=comments 1
=social 1
=abstract start
<hl>use strict</hl> has 3 parts. One of them, also called <hl>use strict "subs"</hl>,
disables the inappropriate use of <b>barewords</b>.
What does that mean?
=abstract end
Without this restriction code like this would work and print "hello".
<code lang="perl">
my $x = hello;
print "$x\n"; # hello
</code>
That's strange in itself as we are used to put strings in quotes but
Perl by default allows <b>barewords</b> - words without quotes - to behave like strings.
The above code would print "hello".
Well, at least until someone added a subroutine called "hello" to the top of
your script:
<code lang="perl">
sub hello {
return "zzz";
}
my $x = hello;
print "$x\n"; # zzz
</code>
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 subroutine
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 <hl>use strict</hl> in your code perl will not allow that bareword
<b>hello</b> in your code, avoiding this type of confusion.
<code lang="perl">
use strict;
my $x = hello;
print "$x\n";
</code>
Gives the following error:
<code>
Bareword "hello" not allowed while "strict subs" in use at script.pl line 3.
Execution of script.pl aborted due to compilation errors.
</code>
<h2>Good uses of barewords</h2>
There are other places where barewords can be used even when <hl>use strict "subs"</hl>
is in effect.
First of all, the names of the subroutines we create are really just barewords.
That's good to have.
Also, when we are referring 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:
<code lang="perl">
use strict;
use warnings;
my %h = ( name => 'Foo' );
print $h{name}, "\n";
</code>
In both cases in the above code "name" is a bareword,
but these are allowed even when use strict is in effect.