The UNIX and Linux Forums  

Go Back   The UNIX and Linux Forums > Top Forums > Shell Programming and Scripting
Google UNIX.COM


Shell Programming and Scripting Post questions about KSH, CSH, SH, BASH, PERL, PHP, SED, AWK and OTHER shell scripts here.

More UNIX and Linux Forum Topics You Might Find Helpful
Thread Thread Starter Forum Replies Last Post
perl array question from going through hash hankooknara Shell Programming and Scripting 2 07-29-2007 06:53 PM
hash,array and perl new2ss Shell Programming and Scripting 3 05-23-2007 08:30 AM
md5 hash a string or char array in SCO jcarter2333 High Level Programming 5 02-08-2007 12:09 PM
Hash within array, within hash, within array... jsmoriss Shell Programming and Scripting 1 07-10-2006 06:26 PM
getting data list into a hash array topcat8 Shell Programming and Scripting 5 03-09-2004 08:02 AM

Reply
 
Submit Tools LinkBack Thread Tools Display Modes
  #1 (permalink)  
Old 05-07-2008
Registered User
 

Join Date: Feb 2005
Posts: 17
Stumble this Post!
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 $file='p.csv';
my %mymap;
$mymap{888} = 444;
$mymap{999} = 333;

open(my $data, '<',$file) or die "Cannot open 'file'\n";
while (my $line=<$data>) {
my @column = split ",", $line;
if ($line =~ /Doc/) {
if (exists $mymap{$column[2]}) {
$column[3]=$mymap{$column[2]};}
foreach my $i (0..$#column) {
if ($i > 0) {
print ",",$column[$i];}
else {
print $column[$i];}
}}
else {
print $line}
}
exit;
Reply With Quote
Forum Sponsor
  #2 (permalink)  
Old 05-07-2008
drl's Avatar
drl drl is offline
Registered User
 

Join Date: Apr 2007
Location: Saint Paul, MN USA / BSD, CentOS, Debian, OS X, Solaris
Posts: 505
Stumble this Post!
Hi.

Here is one way:
Code:
#!/usr/bin/perl

# @(#) p2       Demonstrate building hash (almost) directly from a file.

use warnings;
use strict;

my ($debug);
$debug = 0;
$debug = 1;

chomp( my (%hash) = map { split "," } my (@a) = <> );

foreach my $k ( keys %hash ) {
  print " key = $k, value = $hash{$k}\n";
}

exit(0);
Producing (with your data on file "data1"):
Code:
% ./p2 data1
 key = 888, value = 444
 key = 999, value = 333
See perl man pages or perldoc for details ... cheers, drl

Last edited by drl; 05-07-2008 at 06:59 PM. Reason: Minor typo
Reply With Quote
Google The UNIX and Linux Forums
Reply

Thread Tools
Display Modes




All times are GMT -7. The time now is 04:54 AM.


Powered by: vBulletin, Copyright ©2000 - 2006, Jelsoft Enterprises Limited.
The UNIX and Linux Forums Content Copyright ©1993-2008 The CEP Blog All Rights Reserved -Ad Management by RedTyger Visit The Global Fact Book

Content Relevant URLs by vBSEO 3.2.0