Skip to content

Commit 7988a7c

Browse files
committed
[perlvar] $_, $/ and $!
1 parent 88abdef commit 7988a7c

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

lib/perlvar.pod

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,70 @@
22
33
=head1 perlvar - list of known magical variables
44
5+
=head2 Often-Used Variables
6+
7+
# TODO: find a better heading
8+
9+
There are three special variables that are available in every block:
10+
11+
=begin table
12+
13+
Variable Meaning
14+
15+
$_ topic variable
16+
$/ regex match
17+
$! exceptions
18+
19+
=end table
20+
21+
=head3 $_
22+
23+
C<$_> is the topic variable. It is the default parameter for blocks that do
24+
not have an explicit signature, so constructs like C<for @array { ... }>
25+
and C<given $var { ... }> binds to C<$_> simply by invoking the block.
26+
27+
for <a b c> { say $_ } # sets $_ to 'a', 'b' and 'c' in turn
28+
say $_ for <a b c>; # same, even though it's not a block
29+
given 'a' { say $_ } # sets $_ to 'a'
30+
say $_ given 'a'; # same, even though it's not a block
31+
32+
C<CATCH> blocks set C<$_> to the exception that was caught. The C<~~>
33+
smart-match operator sets C<$_> on the right-hand side expression to the
34+
value of the left-hand side.
35+
36+
Calling a method on C<$_> can be shortened by leaving off the variable name:
37+
38+
.say; # same as $_.say
39+
40+
C<m/regex/> and C</regex/> regex matches and C<s/regex/subst/> substitutions
41+
work on C<$_>.
42+
43+
=head3 $/
44+
45+
C<$/> is the match variable. It stores the result of each regex match, and
46+
usually contains objects of type L<Match>.
47+
48+
'abc 12' ~~ /\w+/; # sets $/ to a Match object
49+
say $/.Str; # abc
50+
51+
The C<Grammar.parse> method also sets the caller's C<$/> to the resulting
52+
L<Match> object.
53+
54+
Other match variables are aliases to elements of C<$/>:
55+
56+
$0 # same as $/[0]
57+
$1 # same as $/[1]
58+
$<named> # same as $/<named>
59+
60+
=head3 $!
61+
62+
C<$!> is the error variable. If a C<try> block or statement prefix catches
63+
an exception, that exception is stored in C<$!>. If no exception was caught,
64+
C<$!> is set to the C<Any> type object.
65+
66+
Note that C<CATCH> blocks I<do not> set C<$!>. Rather they set C<$_> inside
67+
the block to the caught exception.
68+
569
=head2 Compile-time "constants"
670
771
$?FILE Which file am I in?

0 commit comments

Comments
 (0)