【问题标题】:Creating a hashmap using perl split function使用 perl 拆分函数创建哈希图
【发布时间】:2016-05-03 20:36:58
【问题描述】:

我正在尝试从文本文件创建哈希图。文本文件的设置方式如下。

(integer)<-- varying white space --> (string value) 
    .                .                      .
    .                .                      .
    .                .                      . 
(integer)<-- varying white space --> (string value)

例如:

   5           this is a test
  23        this is another test
 123         this is the final test

我想要做的是将键分配给整数,然后将整个字符串分配给值。我正在尝试类似

%myHashMap;

while(my $info = <$fh>){
    chomp($info);
    my ($int, $string) = split/ /,$info;
    $myHashMap{$int} = $string;
}

这不起作用,因为我在字符串中有空格。有没有办法清除初始空白,获取整数,将其分配给 $int,然后清除空白直到到达字符串,然后将该行上的剩余文本放入我的 $string 值?

【问题讨论】:

    标签: perl io hashmap


    【解决方案1】:

    你可以替换

    split / /, $info      # Fields are separated by a space.
    

    split / +/, $info     # Fields are separated by spaces.
    

    或更一般的

    split /\s+/, $info    # Fields are separated by whitespace.
    

    但您仍然会面临前导空格的问题。要忽略这些,请使用

    split ' ', $info
    

    这种特殊情况在空格上拆分,忽略前导空格。

    别忘了告诉 Perl 你最多期望两个字段!

    $ perl -E'say "[$_]" for split(" ", "  1   abc def ghi", 2)'
    [1]
    [abc def ghi]
    

    另一种选择是使用以下内容:

    $info =~ /^\s*(\S+)\s+(\S.*)/
    

    【讨论】:

      【解决方案2】:

      您只需将空白处的每一行文本分成两个字段

      此示例程序假定输入文件作为参数在命令行上传递。我使用Data::Dump 只是为了显示生成的哈希结构

      use strict;
      use warnings 'all';
      
      my %data;
      
      while ( <DATA> ) {
          s/\s*\z//;
          my ($key, $val) = split ' ', $_, 2;
          next unless defined $val;  # Ensure that there were two fields
          $data{$key} = $val;
      }
      
      use Data::Dump;
      dd \%data;
      

      输出

      {
        5   => "this is a test",
        23  => "this is another test",
        123 => "this is the final test",
      }
      

      【讨论】:

        【解决方案3】:

        首先你清除初始空白使用这个

        $info =~ s/^\s+//g;
        

        第二个整数和字符串之间有两个以上的空格,所以使用这样的拆分来给两个空格加上加号

        split/  +/,$info;
        

        代码是

        use strict;
        use warnings;
        
        my %myHashMap;
        
        while(my $info = <$fh>){
            chomp($info);
            $info =~ s/^\s+//g;
            my ($int, $string) = split/  +/,$info;
            $myHashMap{$int} = $string;
        }
        

        【讨论】:

          猜你喜欢
          • 2013-12-20
          • 2011-05-08
          • 2011-04-20
          • 2018-08-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-08-27
          • 1970-01-01
          相关资源
          最近更新 更多