2016-10-10 30 views
1

私は常に混乱しているか、perlでハッシュを処理する方法がわかりません。だからここハッシュのPerlプッシュ値

は、問題となっている全体を考慮

、私は以下のハッシュでキーの名前を変更しようとしています。 %のnew_hashの

my %hash_new = { 
    'customername' => 'Lee & toys', 
    'employee_name' => 'Checngwang', 
    'customer_id' => 'X82349K', 
    'customer_address' => 'classic denver ranch, meadows drive', 
    'types' => 'category la', 
}; 

my %selectCols = ('customername' => 'CUSTOMERNAME','employee_name' => 'EMP_NAME','customer_id' => 'cusid','customer_address' => 'cusaddr','types' => 'Typs'); 

my %new_hash =(); 

foreach my $hash_keys (keys %hash_new){ 
    my $newKey = $selectCols{$hash_keys}; 
    $new_hash{$newKey} = $hash_new{$hash_keys}; 
} 

print Dumper %new_hash; 

出力してください、以下のように連続した文字列のキーと値の組み合わせのようなものである

CUTOMERNAMELee & toysEMP_NAMEChecngwangcus_idX82349Kcusaddrclassic denver ranch, meadows driveTypscategory la 

しかし、これに代えて、私は

$VAR1 = { 
     'CUSTOMERNAME' => 'Lee & toys', 
     'EMP_NAME' => 'Checngwang', 
     'cusid' => 'X82349K', 
     'cusaddr' => 'classic denver ranch, meadows drive', 
     'Typs' => 'category la', 
    }; 

、のようなハッシュを必要としますこの周りに私を助けて!

+1

すみません、少し拡大しなければなりません。あなたが求めていることに従うことができません。私はあなたのコード例では何も印刷ステートメントが表示されません。 – Sobrique

+0

あなたは大丈夫です!私はちょうど印刷ステートメントを更新しました – Raja

+0

私は混乱しています。あなたの入力は何ですか?また、希望する出力は何ですか? – yonyon100

答えて

0

私が正しくあなたを理解している場合、これは動作します:

#!/usr/bin/perl 
use strict; 
use warnings; 
use Data::Dumper; 


my %hash_new = (
    'customername' => 'Lee & toys', 
    'employee_name' => 'Checngwang', 
    'customer_id' => 'X82349K', 
    'customer_address' => 'classic denver ranch, meadows drive', 
    'types' => 'category la' 
); 

my %selectCols = (
    'customername' => 'CUSTOMERNAME', 
    'employee_name' => 'EMP_NAME', 
    'customer_id' => 'cusid', 
    'customer_address' => 'cusaddr', 
    'types' => 'Typs' 
); 

my %new_hash =(); 

foreach my $hash_keys (keys %hash_new){ 
    my $newKey = $selectCols{$hash_keys}; 
    $new_hash{$newKey} = $hash_new{$hash_keys}; 
} 

print Dumper \%new_hash; 

私はあなたのコードに変更したコードのみ%hash_new()の代わり{}を使用していたし、Dumper文で%を免れました。 Dumperはハッシュではなく参照を期待しているため、%はエスケープする必要があります(Dumperで使用されている他のすべてのPerl変数タイプについても同様です)。

出力:

$VAR1 = { 
     'Typs' => 'category la', 
     'cusaddr' => 'classic denver ranch, meadows drive', 
     'EMP_NAME' => 'Checngwang', 
     'cusid' => 'X82349K', 
     'CUSTOMERNAME' => 'Lee & toys' 
    }; 

また、%hash_new%new_hashのような紛らわしい名前を使用しないでください。それはうまく混乱している。

+0

変数の混乱をおかけして申し訳ありません!それはうまく動作します:) – Raja

+0

@ Yadheendran no harm done :) – yonyon100

関連する問題