[英]Perl string comparison in text file
我正在编写一个要由 Perl 脚本处理的抽象指令文件。 每行的格式为 - “指令操作数 1 操作数 2 ...”
因此,如果我有一个喜欢 - “copy dest src”,我想首先检查该行的第一个单词是否说“copy”并相应地继续。 如何使用 Perl 执行此操作?
如果需要,这可以在没有正则表达式的情况下完成。 在空白处拆分,检查第一个单词是否等于“copy”,例如:
echo 'copy foo bar\nbaz' | perl -lane 'print if $F[0] eq q{copy};'
Output:
copy foo bar
Perl 单行代码使用这些命令行标志:
-e
:告诉 Perl 查找内联代码,而不是在文件中。
-n
:一次循环输入一行,默认将其分配给$_
。
-l
:在执行内联代码之前去除输入行分隔符(默认为 *NIX 上的"\n"
),并在打印时去除 append。
-a
:在空格或-F
选项中指定的正则表达式上将$_
拆分为数组@F
。
您应该首先阅读 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// 是如何工作的。 你需要的一切都在那个网站上。
祝你好运。
我会使用调度表。 像这样的东西:
# 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";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.