Perl 只打印散列的一部分

Perl 只打印散列的一部分,perl,Perl,因此,我在perl设置中有一个哈希,每个字段有多个值,我使用它将数据推送到哈希中: push@{$user{$infoName},$information。 一个用户有3个我最喜欢的节目,全部存储为 {'favourite_TV_shows' => [ 'A Country Practice', 'All Saints', 'Falling Skies' ], 'weight' => [ '53kg' ]} 其中一些用户信息是私有的,例如权重,因此我要显示的字段存储在数组中@fie

因此,我在perl设置中有一个哈希,每个字段有多个值,我使用它将数据推送到哈希中:
push@{$user{$infoName},$information。
一个用户有3个我最喜欢的节目,全部存储为

{'favourite_TV_shows' => [ 'A Country Practice', 'All Saints', 'Falling Skies' ], 'weight' => [ '53kg' ]}
其中一些用户信息是私有的,例如权重,因此我要显示的字段存储在数组中
@fieldsToPrint=['username','favorite\u TV\u shows']

如何编写foreach循环以仅打印feildstorprint数组中的字段。 以下是我迄今为止的尝试

foreach ($user{$infoName} == @fieldsToPrint){
   #print
} 

只需在
@fieldsToPrint
数组上迭代,跳过那些没有值的键:

use strict;
use warnings;

my @fieldsToPrint = ( 'username', 'favourite_TV_shows' );

my %user = (
    'favourite_TV_shows' => [ 'A Country Practice', 'All Saints', 'Falling Skies' ],
    'weight'             => ['53kg'],
);

for my $key (@fieldsToPrint) {
    next if !$user{$key};
    print "$key = ", join(', ', @{ $user{$key} }), "\n";
}
产出:

favourite_TV_shows = A Country Practice, All Saints, Falling Skies