文本文件中的 Perl 字符串比较
Perl string comparison in text file
我正在编写要由 Perl 脚本处理的抽象指令文件。每行的格式都是 - "instruction operand1 operand2 ..."
因此,如果我有类似“copy dest src”这样的字样,我想首先检查该行的第一个单词是否为“copy”,然后进行相应操作。如何使用 Perl 执行此操作?
您应该首先阅读 Perl 文档。你问的很琐碎。
https://perldoc.perl.org/perl#Tutorials
这是一个非常简短的示例,可以帮助您入门。
while (my $line = <$FILE_HANDLE>) {
if ($line =~ m/^copy\b/) {
# do something
}
}
阅读正则表达式教程 (https://perldoc.perl.org/perlretut) 了解 m// 的工作原理。您需要的一切都在那个网站上。
祝你好运。
如果需要,这可以在没有正则表达式的情况下完成。在空白处拆分,检查第一个字是否等于“copy”,例如:
echo 'copy foo bar\nbaz' | perl -lane 'print if $F[0] eq q{copy};'
输出:
copy foo bar
Perl 单行代码使用这些命令行标志:
-e
: 告诉 Perl 查找内联代码,而不是在文件中。
-n
:一次循环输入一行,默认分配给 $_
。
-l
: 在执行内联代码之前去除输入行分隔符(默认情况下在 *NIX 上为 "\n"
),并在打印时附加它。
-a
: 在空格或 -F
选项中指定的正则表达式上将 $_
拆分为数组 @F
。
另请参见:
perldoc perlrun
: how to execute the Perl interpreter: command line switches
我会使用调度程序 table。像这样:
# Define a subroutine for each of your commands
sub my_copy {
my ($source, $dest) = @_;
# other stuff
}
# Set up a hash where the keys are the names of the
# commands and the values are references to the
# subroutines
my %commands = (
copy => \&my_copy,
# other commands here
);
# Then, in the main processing section...
my ($cmd, @params) = split /\s+/, $input_line;
if (exists $commands{$cmd}) {
# execute the subroutine
$commands{$cmd}->(@params);
} else {
warn "'$cmd' is not a valid command.\n";
}
我正在编写要由 Perl 脚本处理的抽象指令文件。每行的格式都是 - "instruction operand1 operand2 ..."
因此,如果我有类似“copy dest src”这样的字样,我想首先检查该行的第一个单词是否为“copy”,然后进行相应操作。如何使用 Perl 执行此操作?
您应该首先阅读 Perl 文档。你问的很琐碎。
https://perldoc.perl.org/perl#Tutorials
这是一个非常简短的示例,可以帮助您入门。
while (my $line = <$FILE_HANDLE>) {
if ($line =~ m/^copy\b/) {
# do something
}
}
阅读正则表达式教程 (https://perldoc.perl.org/perlretut) 了解 m// 的工作原理。您需要的一切都在那个网站上。
祝你好运。
如果需要,这可以在没有正则表达式的情况下完成。在空白处拆分,检查第一个字是否等于“copy”,例如:
echo 'copy foo bar\nbaz' | perl -lane 'print if $F[0] eq q{copy};'
输出:
copy foo bar
Perl 单行代码使用这些命令行标志:
-e
: 告诉 Perl 查找内联代码,而不是在文件中。
-n
:一次循环输入一行,默认分配给 $_
。
-l
: 在执行内联代码之前去除输入行分隔符(默认情况下在 *NIX 上为 "\n"
),并在打印时附加它。
-a
: 在空格或 -F
选项中指定的正则表达式上将 $_
拆分为数组 @F
。
另请参见:
perldoc perlrun
: how to execute the Perl interpreter: command line switches
我会使用调度程序 table。像这样:
# Define a subroutine for each of your commands
sub my_copy {
my ($source, $dest) = @_;
# other stuff
}
# Set up a hash where the keys are the names of the
# commands and the values are references to the
# subroutines
my %commands = (
copy => \&my_copy,
# other commands here
);
# Then, in the main processing section...
my ($cmd, @params) = split /\s+/, $input_line;
if (exists $commands{$cmd}) {
# execute the subroutine
$commands{$cmd}->(@params);
} else {
warn "'$cmd' is not a valid command.\n";
}