Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: Using Split to load a hash

by tanyeun (Sexton)
on Aug 20, 2006 at 13:12 UTC ( [id://568424]=note: print w/replies, xml ) Need Help??


in reply to Using Split to load a hash

I often use regex and arrays to manage this kind of data
#!/usr/bin/perl -w open(FH, "file.csv"); # assume you have three columns of your file my (@col1, @col2, @col3); my $i = 0; while(<FH>){ if(/(\S+),(\S+),(\S+)/){ $col1[$i] = $1; $col2[$i] = $2; $col3[$i] = $3; $i++; } } print "columns:$i\n"; print "subject:\t"; for(0..2) {print "$col1[$_]\t"}; print "\n"; print "grade:\t\t"; for(0..2) {print "$col2[$_]\t"}; print "\n"; print "rank:\t\t"; for(0..2) {print "$col3[$_]\t"}; print "\n";
maybe it's not a concise way
but I find it useful
any comments will be pleased^_^

Replies are listed 'Best First'.
Re^2: Using Split to load a hash
by wfsp (Abbot) on Aug 20, 2006 at 13:59 UTC
    If it's useful it's useful! :-)

    Perhaps you could consider loading you data into one data structure instead of three arrays.

    You might also want a more general purpose approach where it would be easier to change the number and name of the columns.

    Putting aside the question of commas inside the fields and any other error checking one approach might be like this.

    It creates an array of hashes. If you were thinking of using something like HTML::Template for your output this would be very handy! :-)

    #!/usr/bin/perl use strict; use warnings; use Data::Dumper; my @AoH; my @fields = qw(subject grade rank); while (my $record = <DATA>){ chomp $record; my @values = $record =~ /([^,]+)/g; push @AoH, { map {$fields[$_] => $values[$_]} (0..$#fields) }; } print Dumper \@AoH; __DATA__ english,1,1 history,2,2 science,3,3 biology,4,4
    output:
    ---------- Capture Output ---------- > "C:\Perl\bin\perl.exe" _new.pl $VAR1 = [ { 'subject' => 'english', 'grade' => '1', 'rank' => '1' }, { 'subject' => 'history', 'grade' => '2', 'rank' => '2' }, { 'subject' => 'science', 'grade' => '3', 'rank' => '3' }, { 'subject' => 'biology', 'grade' => '4', 'rank' => '4' } ]; > Terminated with exit code 0.

    Hope that helps.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://568424]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (3)
As of 2024-04-26 00:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found