【问题标题】:Reading multiple file locations and storing them in different arrays/hash in perl读取多个文件位置并将它们存储在 perl 中的不同数组/哈希中
【发布时间】:2013-06-18 02:52:34
【问题描述】:

我有一个目录 txt 文件,其中包含分类为地址文件和名称文件的不同文件的文件位置路径

目录文件看起来像

Names FIles
[
name file 1 location

name file 2 location
....
]

Address Files
[
address file1 location

address file2 location
....
]

我想读取这个目录文件并将所有名称文件和地址文件存储在名称和地址数组/哈希中。

我是 perl 新手。所以任何帮助都将不胜感激

谢谢

【问题讨论】:

    标签: arrays perl hash


    【解决方案1】:

    我的第一反应是用while 读入文件,并有两个变量作为标志。当您遇到Names Files 行时,您将一个标志设置为1。在前面提到的while 循环中,您有一个if 语句来检查是否设置了标志。如果是,则将后续行(名称位置)读入您选择的数组或散列中。当您遇到Address Files 行时,将第一个标志改回 0,并设置第二个标志,将这些行发送到您的地址数据结构。

    更新:

    一般来说,展示您已经尝试过的东西是一个好主意 - 为将来记住一些东西。
    也就是说,我们都曾在某个时候对此感到陌生。代码可能有点像这样:

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    my ($nameflag, $addressflag);
    my %namehash;
    my %addresshash;
    
    while (<>) {
    
        chomp;
    
        # Setting the flags
        if ($_ eq 'Names Files') {
            $nameflag = 1;
            $addressflag = 0;
            next;
        } elsif ($_ eq 'Address Files') {
            $nameflag = 0;
            $addressflag = 1;
            next;
        } elsif (/^(\[|\])$/) {
            # Assuming you want to ignore those brackets
            next;
        }
    
        my @line = split;
    
        # Assuming your fields can be split on whitespace,
        # that the first field is the (unique) file name, and the
        # second field is the location
    
        if ($nameflag) {
            $namehash{$line[0]} = $line[1];
        } elsif ($addressflag) {
            $addresshash{$line[0]} = $line[1];
        }
    
    }
    
    # Then whatever you want to do with those hashes
    

    你需要更多的时间来忽略那些空行,但这应该足以让你开始。

    【讨论】:

    • 嘿,谢谢,你能用标志告诉我结构吗...对不起,我是新手
    【解决方案2】:

    你想做的似乎是

    #!/usr/bin/env perl
    
    my(@names, @addresses);
    
    while( <DATA> ) {
      chomp;
      next if /^\s*\[*\s*$/;
      if( /Names FIles/ ... /]/ ) {
        push @names, $_;
        next
      }
      if( /Address Files/ ... /]/ ) {
        push @addresses, $_
      }
    }
    
    use DDP; p @names; p @addresses;
    
    __DATA__
    Names FIles
    [
    name file 1 location
    
    name file 2 location
    ....
    ]
    
    Address Files
    [
    address file1 location
    
    address file2 location
    ....
    ]
    

    【讨论】:

    • 谢谢大家 这很有帮助。我使用带有标志的 while 循环来解析和推送函数以将数据存储在相应的数组中
    猜你喜欢
    • 2012-05-27
    • 1970-01-01
    • 1970-01-01
    • 2021-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多