What is 1 dollar in Perl?

What is $1? Is this a match found for (\d+)?

$line =~ /^(\d+)\s/; 
next if(!defined($1) ) ;
$paperAnnot{$1} = $line;
+3
source share
3 answers

you're right, $1means the first capture group, in your example this(\d+)

+4
source

Oops! This is a group match. Seeing nextthere, possibly in a loop. However, the best way to handle what you have is to use a conditional expression and test the regular expression:

if ( $line =~ /^(\d+)\s/ ) {
    $paperAnnot{$1} = $line;
}

or even better, give $ 1 a name to make it self-documenting:

if ( $line =~ /^(\d+)\s/ ) {
    my $index = $1;
    $paperAnnot{$index} = $line;
}

In addition, you can find more about $1and his brothers at perldoc perlvar .

Perl 5.10 :

use 5.010; # or newer
...
if ( $line =~ /^(?<linenum>\d+)\s/ ) {
    $paperAnnot{ $+{linenum} } = $line;
}

perldoc perlre.

+3

Yes, everything written in parentheses is assigned to magic variables $ 1, $ 2, $ 3 .... If regexp does not match, they will be undefined.

+2
source

Source: https://habr.com/ru/post/1743307/


All Articles