【问题标题】:Perl string comparison in text file文本文件中的 Perl 字符串比较
【发布时间】:2021-03-16 04:36:31
【问题描述】:

我正在编写一个要由 Perl 脚本处理的抽象指令文件。每一行的格式为 - “指令操作数 1 操作数 2 ...”

因此,如果我有一个类似“copy dest src”的内容,我想首先检查该行的第一个单词是否为“copy”并相应地继续。如何使用 Perl 做到这一点?

【问题讨论】:

  • 简单答案:正则表达式。硬答案:正则表达式。
  • 你如何定义一个词?使用split ' ', $_ 分割空格。

标签: string perl scripting


【解决方案1】:

如果需要,这可以在没有正则表达式的情况下完成。在空白处拆分,检查第一个单词是否等于“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

【讨论】:

    【解决方案2】:

    您应该从阅读 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// 的工作原理。您需要的一切都在该网站上。

    祝你好运。

    【讨论】:

      【解决方案3】:

      我会使用调度表。像这样的:

      # 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";
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-15
        • 2014-05-31
        • 1970-01-01
        • 1970-01-01
        • 2016-06-16
        • 1970-01-01
        相关资源
        最近更新 更多