将2个数组/哈希值合并为1个变量Perl

时间:2017-08-03 19:14:51

标签: arrays perl hash

我有两个在表单提交时返回的变量。我需要将值合并为1个变量,以后我可以使用它来创建SQL 如何获得所有值的并集结果: 即location_setting ='409','405'和Status ='501','137','124'

这是我当前的代码,但只吐出来自h2的值

use Data::Dumper;

my $h1 =  {  'location_setting' => [ '409' ], 'status' => [ '501' ] };

my $h2 = {  'status' => [ '137', '124' ], 'location_setting' => ['405'], 'classification' => ['0']}; 

my $x = {%$h1, %$h2};

print Dumper $x;

2 个答案:

答案 0 :(得分:2)

fs = 1000; %Sample frequency (Hz)
tlim = [0,1];
t = (tlim(1)/fs:1/fs:tlim(2)-1/fs)'; %Sample domain (t)
N = numel(t);

f = @(t) 100-30*(t-0.5).^2; %Frequency function (Hz)
I = sin(2*pi*f(t).*t); %Sample function

w = 201; %window width
ww=floor(w/2); %window half-width

for i=0:2:N-w

    %Take the FFT of a portion of I, convolved with a Hamming window
    II = 1/(fs*N)*abs(fft(I((1:w)+i).*hamming(w))).^2;
    II = II(1:floor(numel(II)/2));
    p = (0:fs/w:(fs/2-fs/w))';

    %Find approximate FFT maximum
    [~,maxIx] = max(II);
    maxLoc = p(maxIx);

    %Fit the resulting FFT with a Gaussian function
    gauss = @(c,x) c(1)*exp(-(x-c(2)).^2/(2*c(3)^2));
    op = optimset('Display','off');
    mdl = lsqcurvefit(gauss,[max(II),maxLoc,10],p,II,[],[],op);    

    %Generate diagnostic plots
    subplot(3,1,1);plot(p,II,p,gauss(mdl,p))
    line(f(t(i+ww))*[1,1],ylim,'color','r');

    subplot(3,1,2);plot(t,I);
    line(t(1+i)*[1,1],ylim,'color','r');line(t(w+i)*[1,1],ylim,'color','r')

    subplot(3,1,3);plot(t(i+ww),f(t(i+ww)),'b.',t(i+ww),mdl(2),'r.');
    hold on
    xlim([0,max(t)])
    drawnow
end
hold off

如果您有大量哈希值或可变数量的哈希值,

use List::Util qw( uniq );

my %h =
   map {
      $_ => [
         uniq
            $h1->{$_} ? @{ $h1->{$_} } : (),
            $h2->{$_} ? @{ $h2->{$_} } : (),
      ]
   } 
      uniq
         keys(%$h1), keys(%$h2);

答案 1 :(得分:1)

use Data::Dumper;
use List::Util qw( uniq );

my $h1 =  {  'location_setting' => [ '409' ], 'status' => [ '501' ] };

my $h2 = {  'status' => [ '137', '124' ], 'location_setting' => [], 'classification' => ['0']}; 

my %x;
foreach my $h1key (keys %{$h1}) {
    push @{$x{$h1key}}, @{${$h1}{$h1key}};
}

foreach my $h2key (keys %{$h2}) {
    push @{$x{$h2key}}, @{${$h2}{$h2key}};
}

@$_ = uniq @$_
   for values(%x);

my $x = \%x;
print Dumper $x;