CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Adding data into Hashes

 



why_perl
Novice

Jan 16, 2005, 1:06 PM

Post #1 of 3 (538 views)
Adding data into Hashes Can't Post

Thanx KevinR for your replies on my last thread.

What is the best way to add data from a flat-file DB to a hash?

e.g.

Let's say I have a FF DB with the contents:

Header:
Item1|Item2|
Footer:
Item1|Item2|

Basically, i'm trying to figure out how the easiest most reliable way of referencing specific data from the FF DB.

In the above example, I would like to have the ability to reference "Header" which will give me the data in the line that's below it. Same for "Footer."

Thanx!


KevinR
Veteran


Jan 16, 2005, 3:38 PM

Post #2 of 3 (532 views)
Re: [why_perl] Adding data into Hashes [In reply to] Can't Post

here is one way, if you are sure of the data file being in the correct format:


Code
open (FILE,"yourfile.xxx") or die "$!"; 
my %hash = <FILE>;
close FILE;

print "$hash{'Header:'}";
print "$hash{'Footer:'}";


the keys and values will still have the newlines on the end so you may need to chomp them if its a problem.
-------------------------------------------------


(This post was edited by KevinR on Jan 16, 2005, 3:44 PM)


davorg
Thaumaturge / Moderator

Jan 17, 2005, 6:15 AM

Post #3 of 3 (525 views)
Re: [why_perl] Adding data into Hashes [In reply to] Can't Post

I'd be tempted to add a couple more steps to KevinR's answer.


Code
open (FILE,"yourfile.xxx") or die "$!";  
my @file = <FILE>;
close FILE;

chomp @file; # remove newlines
s/:$// for @file; # remove : from keys

my %hash = @file;

print $hash{Header};
print $hash{Footer};


--
Dave Cross, Perl Hacker, Trainer and Writer
http://www.dave.org.uk/
Get more help at Perl Monks

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives