/* start of maker a_b.c[0] */
/* start of maker a_b.c[1] */
maker ( "a_b.c[0]" )
maker ( "a_b.c[1]" )
如何提取雙引號內的字串并將它們存盤到陣列中?這是我嘗試過的。
open(file, "P2.txt");
@A = (<file>) ;
foreach $str(@A)
{
if($str =~ /"a_b.c"/)
{
print "$str \n";
}
}
注意:只有雙引號內的內容必須存盤到陣列中。如果您在斜杠中看到示例的第一行,您將看到我想要匹配的相同字串。那不應該被列印出來。所以只應將雙引號內的字串存盤到陣列中。即使相同的字串在沒有雙引號的情況下在其他地方重復,也不應該被列印出來。.
uj5u.com熱心網友回復:
這不是在雙引號中查找字串。它是關于定義與您要查找的行匹配的模式(正則運算式)。
這是我可以對您的代碼進行的最小更改,以使其正常作業:
open(file, "P2.txt");
@A = (<file>) ;
foreach $str(@A)
{
if($str =~ /"a_b.c/) # <=== Change here
{
print "$str \n";
}
}
我所做的就是從匹配運算式中洗掉結束雙引號。因為你不關心后面是什么,所以你不需要在正則運算式中指定它。
我應該指出,這并不完全正確。在正則運算式中,點具有特殊含義(它的意思是“匹配此處的任何字符”),因此要匹配實際的點(這是您想要的),您需要使用反斜杠對點進行轉義。所以應該是:
if($str =~ /"a_b\.c/)
重寫以使用一些更現代的 Perl 實踐,我會這樣做:
# Two safety nets to find problems in your code
use strict;
use warnings;
# say() is a better print()
use feature 'say';
# Use a variable for the filehandle (and declare it with 'my')
# Use three-arg version of open()
# Check return value from open() and die if it fails
open(my $file, '<', "P2.txt") or die $!;
# Read data directly from filehandle
while ($str = <$file>)
{
if ($str =~ /"a_b\.c/)
{
say $str;
}
}
您甚至可以使用隱式變數 ( $_) 和陳述句修飾符來使您的回圈更加簡單。
while (<$file>) {
say if /"a_b\.c/;
}
uj5u.com熱心網友回復:
查看您提供的示例輸入,該任務可以解釋為“將單個字串引數提取到看起來像函式呼叫的東西”。似乎在 C 風格的注釋中增加了不匹配的復雜性。為此,請注意perlfaq -q comment。
正如 FAQ 條目所示,忽略任意 C 樣式注釋中的內容通常并非易事。我決定嘗試C::Tokenize來幫助:
#!/usr/bin/env perl
use strict;
use warnings;
use feature 'say';
use C::Tokenize qw( tokenize );
use Const::Fast qw( const );
use Path::Tiny qw( path );
sub is_open_paren {
($_[0]->{type} eq 'grammar') && ($_[0]->{grammar} eq '(');
}
sub is_close_paren {
($_[0]->{type} eq 'grammar') && ($_[0]->{grammar} eq ')');
}
sub is_comment {
$_[0]->{type} eq 'comment';
}
sub is_string {
$_[0]->{type} eq 'string';
}
sub is_word {
$_[0]->{type} eq 'word';
}
sub find_single_string_args_in_invocations {
my ($source) = @_;
my $tokens = tokenize(path( $source )->slurp);
for (my $i = 0; $i < @$tokens; $i) {
next if is_comment( $tokens->[$i] );
next unless is_word( $tokens->[$i] );
next unless is_open_paren( $tokens->[$i 1] );
next unless is_string( $tokens->[$i 2] );
next unless is_close_paren( $tokens->[$i 3]);
say $tokens->[$i 2]->{string};
$i = 3;
}
}
find_single_string_args_in_invocations($ARGV[0]);
根據您的輸入,它會產生:
C:\Temp> perl t.pl test.c
"a_b.c[0]"
"a_b.c[1]"
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/344832.html
標籤:perl
