【问题标题】:Perl - concatenating a undefined number of strings into one stringPerl - 将未定义数量的字符串连接成一个字符串
【发布时间】:2015-04-14 21:22:23
【问题描述】:

我需要用 Perl 连接未定义数量的字符串来创建一个更大的字符串。

$concatenated_string = $string1 . $string2 . $string3 #..等等,用于在程序之前打开的文件中提供的所有字符串。

我只是一个初学者,但我在这里找不到任何与此相关的问题。非常感谢任何帮助。

【问题讨论】:

  • 请出示您的代码。
  • 需要更多代码作为示例。将文件的内容连接到字符串中相对容易,但在某种程度上取决于您要完成的工作。

标签: string perl concatenation


【解决方案1】:

作为I have mentioned elsewhere:

当您发现自己在变量名称中添加整数后缀时,请想“我应该使用数组”。

那么你可以使用join('', @strings)

【讨论】:

    【解决方案2】:

    我猜了一下,因为您没有太多示例代码。

    但是你有没有考虑过这样的事情:

    open ( my $input_fh, "<", "filename" ) or die $!;
    my $concatenated_string;
    while ( my $line = <$input_fh> ) {
        chomp ( $line ); #if you want to remove the linefeeds.
        $concatenated_string .= $line; 
    }
    

    【讨论】:

      【解决方案3】:
      #!/usr/bin/env perl
      
      # Modern Perl is a book every one should read
      use Modern::Perl '2013';
      
      # Declaring array to store input
      my @info;
      
      # Using a loop control to store unknow number of entries
      while (<STDIN>) {    # Reading an undefined number of strings from STDIN
      
        # Removing the \n
        chomp;
      
        # Stacking input value into array
        push(@info, $_);
      }
      
      # printing all entries separated by ","
      say join(', ', @info);
      
      # exit program indicating success (no problem)
      exit 0;
      

      my $stream;
      $stream .= $_ while <STDIN>;
      print $stream;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-02-02
        • 2013-05-15
        • 2017-10-25
        • 2015-05-02
        • 1970-01-01
        • 1970-01-01
        • 2012-04-08
        • 2022-12-17
        相关资源
        最近更新 更多