簡體   English   中英

如何在Perl中將字符串轉換為哈希表

[英]How to convert string to hash table in perl

我有一個來自for循環的字符串:

@file = "/path/window/*_testing_42.csv";


foreach $file(@file) {


$name = $file=~ /(\w*)_testing_42/; #comes from file path
$name = 1$;
print $name; #prints G43B76P90T45

}

我需要從此字符串中獲取4個值(G43,B76,P90,T45)。 我想將它們放入一個散列中,以便可以專門引用每個值。 但是,我要實現的哈希表代碼無法滿足我的預期目的:

 my %hash;



foreach $file(@file) {


    $name = $file=~ /(\w*)_testing_42/; #comes from file path
    $name = 1$;
    print $name; #prints G43B76P90T45



    my($first $second $third $fourth) = $name;
    $hash{"first"} = $first;
    $hash{"second"} = $second;
    $hash{"third"} = $third;
    $hash{"fourth"} = $fourth;

預期的輸出:

    print $fourth; #should print T45


    print $first; #should print G43
    print $third #should print  P90
}

首先,您需要將名稱分為4部分:

my ($first, $second, $third, $fourth) = unpack("(A3)*", $name);

填寫哈希

$hash{"first"} = $first;
$hash{"second"} = $second;
$hash{"third"} = $third;
$hash{"fourth"} = $fourth;

並打印哈希

print $hash{"fourth"};

如果我正確理解了您要做什么,那么@Gever的答案應該可以解決問題。 這是使用正則表達式而不是解壓縮的替代實現:

use 5.010;
use strict;
use warnings;

my @file = glob("/path/window/*_testing_42.csv");

foreach my $file (@file) {
    my($name) = $file =~ /(\w+)_testing_42/;
    my @code = $name =~ /(...)/g;
    say 'Parts found: ', scalar(@code);   # Parts found: 4
    say $code[0];   # G43
    say $code[1];   # B76
    say $code[2];   # P90
    say $code[3];   # T45
}

我使用數組而不是哈希,因為這對我來說更有意義,但是如果您確實想要哈希,則可以這樣做:

foreach my $file (@file) {
    my($name) = $file =~ /(\w+)_testing_42/;
    my %hash;
    @hash{'first', 'second', 'third', 'fourth'} = $name =~ /(...)/g;
    say $hash{first};   # G43
    say $hash{second};  # B76
    say $hash{third};   # P90
    say $hash{fourth};  # T45
}

在這一行:

my($name) = $file =~ /(\w+)_testing_42/;

$name左右的括號很重要,因為它們會強制在列表上下文中評估匹配項,這會返回在(\\w+)中捕獲的正則表達式部分。 如果沒有括號,則將值1分配給$name因為存在1個匹配項。

在哈希(稱為“哈希切片”)中為一系列鍵分配值列表的語法有些令人困惑。 Perl的知道我們正在分配值到%hash ,因為的{后的變量名,但我們把@變量名前,表示我們對散列切片分配多個值。 在變量名之前使用$表示我們正在將哈希值分配給單個值。

我從您的代碼中更改的另一件事是,我在循環內聲明了%hash 這意味着您只能在循環內引用它。 如果在循環外聲明它,則一組值將在處理完每個匹配的文件名后保留,但是散列可能包含來自不同文件名的值,具體取決於上一次迭代中存在多少個字段。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM