Blurman
Blurman

Reputation: 609

Reading text file into hash and accessing values perl

I am trying to read text file content into hash but having some problem reading as well as accessing it.

resctrl_top
    /path/to/a/
vdm05top
    /path/to/b/
    /path/to/c/
    /path/to/d/
    /path/to/e/
    /path/to/f/

The file format will be as above. My desired output is a hash with the non spacing line as key, and the path lines as values. I would like to know also how to access each values for different keys.

resctrl_top => /path/to/a/
vdm05top => /path/to/b/,/path/to/c/,...

Below are the effort I tried:

use strict;
use warnings;
my %hash;
open FILE, "filename.txt" or die $!;
my $key;
while (my $line = <FILE>) {
     chomp($line);
     if ($line !~ /^\s/) {
        ($key) = $line =~ /^\S+/g;
        $hash{$key} = [];
     } else {
        $line =~ s/^\s+//;
        push @{ $hash{$key} }, $line;
     }
 }
 close FILE;

 foreach (keys %hash){
    print "$key => $hash{$key}\n";
 }

Upvotes: 1

Views: 127

Answers (2)

vkk05
vkk05

Reputation: 3222

Try this way:

use strict;
use warnings;
use Data::Dumper;
my %hash;
my $key;
while (my $line = <DATA>) {
     chomp($line);
     if ($line !~ /^\s/) {
        $key = $line;
     } else {
        $line =~ s/\s//g;
        push (@{$hash{$key}} , $line);
     }
}
my %final;
foreach my $k (keys %hash){
        my $val = join(",", @{$hash{$k}});
        $final{$k} = $val; #New hash will have key and respective values
}

print Dumper(\%final);

__DATA__
resctrl_top
    /path/to/a/
vdm05top
    /path/to/b/
    /path/to/c/
    /path/to/d/
    /path/to/e/
    /path/to/f/      

Result:

$VAR1 = {
          'vdm05top' => '/path/to/b/,/path/to/c/,/path/to/d/,/path/to/e/,/path/to/f/',
          'resctrl_top' => '/path/to/a/'
        };

Hope this solves your problem.

Upvotes: 3

Dave Cross
Dave Cross

Reputation: 69224

Here's a pretty simple solution.

#!/usr/bin/perl

use strict;
use warnings;
use feature 'say';

use Data::Dumper; # Just for output

my ($key, %hash); # Declare globals

while (<DATA>) {  # Quick hack - read from DATA
  chomp;

  if (/^\s/) {    # If the line starts with a space
    s/^\s+//;
    push @{$hash{$key}}, $_;
  } else {        # The line is a key
    $key = $_;
  }
}

say Dumper \%hash;

__DATA__
resctrl_top
    /path/to/a/
vdm05top
    /path/to/b/
    /path/to/c/
    /path/to/d/
    /path/to/e/
    /path/to/f/

Upvotes: 0

Related Questions