perl - 在 perl 中散列的数组

标签 perl arrays hash scripting

我有一个源列表,从中我可以选择随机项目并填充目标列表。列表中的项目具有特定格式。例如:

item1{'name'}
item1{'日期'}

等等以及更多领域。

在插入目标列表时,我检查项目上的唯一名称并将其插入该列表。为此,我必须遍历整个目标列表以检查具有给定名称的项目是否存在,如果不存在,则插入它。

我认为如果我再次将目标列表设为散列而不是列表会更好,这样我就可以更快、更有效地查找项目。我是 Perl 的新手,不知道如何做到这一点。任何人,请帮助我如何插入项目,查找特定项目名称以及删除哈希中的项目?

如何将名称和日期作为键并将整个项目作为值?

最佳答案

我的 %hash;

  • 插入带有键 $K 的项目 $V?

    $hash{$K} = $V
  • 查找特定名称/ key $K?
  •     if (exists $hash{$K}) { 
            print "it is in there with value '$hash{$K}'\n";
        } else { 
            print "it is NOT in there\n" 
        }
    
    1. Delete a particular name / key?

      delete $hash{$K}

    2. Make name and date as key and entire item as value?

    Easy Way: Just string everything together

    set: $hash{ "$name:$date" } = "$name:$date:$field1:$field2"
    get: my ($name2,$date2,$field1,$field2) = split ':', $hash{ "$name:$date" }
    del: delete $hash{ "$name:$date" }
    

    更难的方法:在哈希中存储为哈希(谷歌“perl 对象”)

    放:
    my %temp;
    $temp{"name"} = $name;
    $temp{"date"} = $date;
    $temp{"field1"} = $field1;
    $temp{"field2"} = $field2
    
    $hash{"$name:$date"} = \$temp;
    

    得到:
    my $find = exists $hash{"$name:$date"} ? $hash{"$name:$date"} : undef;
    if (defined find) { # i.e. it was found
        printf "field 1 is %s\n", $find->{"field1"}
    } else {
        print "Not found\n";
    }
    

    删除:
    delete $hash{"$name:$date"}
    

    关于perl - 在 perl 中散列的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3199185/

    相关文章:

    javascript - 从 Javascript 调用 perl 文件/函数和函数来更新 HTML

    perl - 使用 CGI 时如何在 perl 中获取 HTTP header

    无法执行系统调用 "execve"

    按字符串搜索 PHP MySQL 表 - 使用散列?

    .net - 找出两个列表之间的差异

    python - 从 Python 运行 Perl 脚本并将输出写入文件时,为什么文件是空的?

    perl - 强制 cmp_deep 在失败时显示哈希中的所有差异

    javascript - 数组访问问题

    javascript - 如何使用 javascript 在 HTML 中的数组中显示访问的(通过 for 循环)对象

    regex - 映射奇怪的行为