Read column into hash


 
Thread Tools Search this Thread
Top Forums Programming Read column into hash
# 1  
Old 01-08-2011
Read column into hash

Hi, I want to read the __DATA__ into hashes with the first word (indented) of each part as key and the rest of the part (an array as value). Each part of the input is identified by the indentation. i.e. "The Skipper", "Professor", "Gilligan" are three identifiers as they do not have indentation, but the rest are indented in my original data (Here I used "_" instead because of the display in the forum post). The out put should be like:
Code:
The Skipper => blue_shirt  hat  jacket  preserver  sunscreen
Professor    => sunscreen  water_bottle  slide_rule
Gilligan       =>  red_shirt  hat  lucky_socks  water_bottle

The code pushes all of the data into a single hash entry, not three. Can anybody give me some help on this?

Thanks a lot!

Yifangt
Code:
#!/usr/bin/perl -w
use strict;
use Data::Dumper;

my %provisions;
my @person;
my @hash_array;

while (<DATA>) {
    if (/^\S.*/) {                 # a person's name (no leading whitespace)
        push @person, $1;
        push @hash_array, $provisions{$person[$#person]};
    } elsif (/^\s+(\w.*)/) {         # word started with indentation as array member as hash value
          push @{$provisions{$person[$#person]}}, $1;  # push the word into array
               } else {
        die "I don't understand: $_";
          }
}
print Dumper %provisions, "\n";

__DATA__
The Skipper
 _blue_shirt
 _hat
 _jacket
 _preserver
 _sunscreen
Professor
 _sunscreen
 _water_bottle
 _slide_rule
Gilligan
 _red_shirt
 _hat
 _lucky_socks
 _water_bottle

The output is:
Code:
$VAR1 = '';
$VAR2 = [
          'blue_shirt',
          'hat',
          'jacket',
          'preserver',
          'sunscreen',
          'sunscreen',
          'water_bottle',
          'slide_rule',
          'red_shirt',
          'hat',
          'lucky_socks',
          'water_bottle'
        ];
$VAR3 = '
';


Last edited by Scott; 01-09-2011 at 03:25 AM.. Reason: Code tags, please...
# 2  
Old 01-08-2011
In:
Quote:
Originally Posted by yifangt
Code:
    if (/^\S.*/) {                 # a person's name (no leading whitespace)
        push @person, $1;
        push @hash_array, $provisions{$person[$#person]};
    }

The hash, $provisions{$person[$#person]} is not defined, so nothing is being pushed onto @hash_array. You need to initialize, with:
Code:
push @hash_array, $provisions{$person[$#person]} = {};


Last edited by m.d.ludwig; 01-08-2011 at 07:01 PM.. Reason: bad editing
# 3  
Old 01-08-2011
reply: Read columns into hash

Thanks ludwig!

Although I thought I defined the hash at the beginning, it seems you got the points: after I changed into your code, the problem is related to this. But it did not work still!
===================Erro message =================
Global symbol "%provisions" requires explicit package name in program.pl" which is the error message from my console.
======================================
Strange! Could not figure out the bug.
More clue?

Thanks again! yifangt
# 4  
Old 01-08-2011
My apologies, it should have [], not {}. But to simplify the inner workings of the while loop:
Code:
  if (/^(\S.*)$/) { # a person's name (no leading whitespace)
    push @person, $1;
    push @hash_array, $provisions{$person[-1]} = [];
    next;
  }

  if (/^\s+(\w.*)/) { # word started with indentation as array member as hash value
    push @{$provisions{$person[-1]}}, $1; # push the word into array
    next;
  }

  die "I don't understand: $_";

In case you are wondering, $person[-1] is also the last element of a list.
# 5  
Old 01-08-2011
reply: Read columns into hash!

Thanks a lot!

First, thank you for the regex line for the person's name. That makes much more sense.

Second, what I was thinking is: each time only one item was pushed into the array, why need the anonymous array []?

I am aware of this case is twisty, and need to digest it a little bit more.

Thank you again!

Yifangt
# 6  
Old 01-08-2011
Were you invoking the script as perl scriptname or ./scriptname??
# 7  
Old 01-08-2011
reply: Read columns into hash!

The first one "perl scriptname".
Does that matter to the result?

The script is working anyway. I modified the code a little bit for the output. Everything is fine now.

Thanks a lot!

Yifangt
Code:
#!/usr/bin/perl -w
use strict;
use Data::Dumper;

my %provisions;
my @person;
my @hash_array;

while (<DATA>) {
    if (/^(\S.*)$/) {         # a person's name (no leading whitespace)
    push @person, $1;
    push @hash_array, $provisions{$person[-1]} = [];
    next;
  }

  if (/^\s+(\w.*)/) { # word started with indentation as array member as hash value
    push @{$provisions{$person[-1]}}, $1; # push the word into array
    next;
  }

  die "I don't understand: $_";
}
#print Dumper @person, "\n";
#print Dumper @hash_array, "\n";
#print Dumper %provisions, "\n";

foreach my $key (keys %provisions) {
    print $key, "\t=>\t", "@{$provisions{$key}}", "\n";
    }

==========Output=======perl program_script.pl======
Code:
Professon    =>    sunscreen water_bottle slide_rule
The Skipper    =>    blue_shirt hat jacket preserver sunscreen
Gilligan    =>    red_shirt hat lucky_socks water_bottle


Last edited by Scott; 01-09-2011 at 03:26 AM.. Reason: Code tags, please...
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Read first column and count lines in second column using awk

Hello all, I would like to ask your help here: I've a huge file that has 2 columns. A part of it is: sorted.txt: kss23 rml.67lkj kss23 zhh.6gf kss23 nhd.09.fdd kss23 hp.767.88.89 fl67 nmdsfs.56.df.67 fl67 kk.fgf.98.56.n fl67 bgdgdfg.hjj.879.d fl66 kl..hfh.76.ghg fl66... (5 Replies)
Discussion started by: Padavan
5 Replies

2. Shell Programming and Scripting

Dynamically parse BibTeX and create hash of hash

Hello gurus, Iam trying to parse following BibTex file (bibliography.bib): @book{Lee2000a, abstract = {Abstract goes here}, author = {Lee, Wenke and Stolfo, Salvatore J}, title = {{Data mining approaches for intrusion detection}}, year = {2000} } @article{Forrest1996, abstract =... (0 Replies)
Discussion started by: wakatana
0 Replies

3. Shell Programming and Scripting

Compare values of hashes of hash for n number of hash in perl without sorting.

Hi, I have an hashes of hash, where hash is dynamic, it can be n number of hash. i need to compare data_count values of all . my %result ( $abc => { 'data_count' => '10', 'ID' => 'ABC122', } $def => { 'data_count' => '20', 'ID' => 'defASe', ... (1 Reply)
Discussion started by: asak
1 Replies

4. Shell Programming and Scripting

Perl Hash:Can not keep hash data in the same order that it was inserted

Can Someone explain me why even using Tie::IxHash I can not get the output data in the same order that it was inserted? See code below. #!/usr/bin/perl use warnings; use Tie::IxHash; use strict; tie (my %programs, "Tie::IxHash"); while (my $line = <DATA>) { chomp $line; my(... (1 Reply)
Discussion started by: jgfcoimbra
1 Replies

5. Shell Programming and Scripting

Read CSV column value based on column name

Hi All, I am newbie to Unix I ve got assignment to work in unix can you please help me in this regard There is a sample CSV file "Username", "Password" "John1", "Scot1" "John2", "Scot2" "John3", "Scot3" "John4", "Scot4" If i give the column name as Password and row number as 4 the... (3 Replies)
Discussion started by: JohnGG
3 Replies

6. Shell Programming and Scripting

PERL: reading 2 column data into Hash file

I am trying to read in a 2 column data file into Perl Hash array index. Here is my code. #!/usr/bin/perl -w use strict; use warnings; my $file = "file_a"; my @line = (); my $index = 0; my %ind_file = (); open(FILE, $file) or die($!); while(<FILE>) { chomp($_); if ($_ eq '') { ... (1 Reply)
Discussion started by: subhap
1 Replies

7. Shell Programming and Scripting

Print Entire hash list (hash of hashes)

I have a script with dynamic hash of hashes , and I want to print the entire hash (with all other hashes). Itried to do it recursively by checking if the current key is a hash and if yes call the current function again with refference to the sub hash. Most of the printing seems to be OK but in... (1 Reply)
Discussion started by: Alalush
1 Replies

8. Shell Programming and Scripting

Read csv into Hash array?

Hi all experts, May I know how to read a csv file and read the content in a hash in PERL? Currently, I hard-coded and defined it in my code. I wanna know how to make up the %mymap hash thru reading the cfg.txt ==== csv file(cfg.txt): 888,444 999,333 === #!/usr/bin/perl my... (1 Reply)
Discussion started by: kinmak
1 Replies

9. UNIX for Dummies Questions & Answers

could sudo read hash passwords? how?

Hello, user ABC is granted sudo rights to start the application. So upon attempting to start the application, user ABC is required to enter its password. If we wanted to user ABC is create a cron job to start the application, how will user ABC feed in the password in the cron job? I know... (0 Replies)
Discussion started by: hemangjani
0 Replies

10. Shell Programming and Scripting

how to read the column and print the values under that column

hi all:b:, how to read the column and print the values under that column ...?? file1 have something like this cat file1 ======= column1, column2,date,column3,column4..... 1, 23 , 12/02/2008,...... 2, 45, 14/05/2008,..... 3, 56, 16/03/2008,..... cat file2 =======... (6 Replies)
Discussion started by: gemini106
6 Replies
Login or Register to Ask a Question