in reply to array of hashes use

You only have one %$record, as declared at the top.

I'm guessing that you probably want to have a new record for each file in the outer while loop, so put the my $record = {} inside that loop.

Replies are listed 'Best First'.
Re^2: array of hashes use
by mimosinnet (Beadle) on Apr 02, 2013 at 00:59 UTC

    Your are right! This code works as expected:

    use strict; use warnings; use Data::Dumper; my (@host, $key, $value, $line, $filename); my $rec_num = 0; my $dirname = "."; opendir( my $dir, $dirname) or die "cant opendir $dirname: $!"; while (defined ($filename = readdir($dir))){ next unless $filename =~ /\w+\.txt/; print "filename: $filename \n"; my $record = {}; open( my $fh , "<", $filename); while ($line = <$fh>){ chomp $line; next if $line =~ /^$/; next if $line =~ /[#{}]/; $line =~ /^\s*(\S+)\s*(\S+)/; $record->{$1} = $2; } close($fh); push @host, $record; $rec_num += 1; } closedir($dir); print Dumper(@host);

    This is the output:

    filename: hosts.txt filename: hosts1.txt $VAR1 = { 'contacts' => 'helpdesk,admin', 'display_name' => 'whplnsweb-dr', 'register' => '1', 'use' => 'xiwizard_windowsserver_host', 'hostgroups' => 'AntiVirus', 'host_name' => 'whplnsweb-dr', 'address' => '172.28.17.115', 'alias' => 'whplnsweb-dr' }; $VAR2 = { 'contacts' => 'helpdesk,admin', 'display_name' => '-------------', 'register' => '1', 'use' => 'test1.txt', 'hostgroups' => 'AntiVirus', 'host_name' => 'test1.txt', 'address' => '-------------', 'alias' => 'test1.txt' };

      Be that as it may, you either use autodie or explicitly check for the return of the open function in case it fails. The same goes for close and closedir.

      If you tell me, I'll forget.
      If you show me, I'll remember.
      if you involve me, I'll understand.
      --- Author unknown to me