Newbie - Reading a file with delimited fields, storing first two fields in a hash

A

AMT2K5

Hello,

I have the following file delimited like this...

userid|lastname|firstname|email|

I want to read the file and store userid as a key and lastname as a
value

How can I do this?

So far my function has the following

sub check{

open FILE, "<users.txt" or die "Can't open 'users.txt'.";

my $line;
my @line;
my %line; //Probably need this


while ($line=<FILE>)
{
chomp($line);
@line = split(/\|/,$line);
}
close(FILE);

}
 
E

Eric Schwartz

AMT2K5 said:
I have the following file delimited like this...

userid|lastname|firstname|email|

I want to read the file and store userid as a key and lastname as a
value

How can I do this?

Use a hash.
So far my function has the following

Functions are good, but ideally we want a complete, runnable program.
That makes it a bit more work for you, but makes it a lot easier for
us to see what's going on.
sub check{

open FILE, "<users.txt" or die "Can't open 'users.txt'.";

Good start; you want to investigate lexical filehandles, and use the
3-argument form of open (perldoc -f open to learn more). You also
need to report the actual error encountered, so you know WHY you can't
open users.txt.

open my $userfile, "<", "users.txt"
or die "Can't open users file: $!"
my $line;
my @line;
my %line; //Probably need this

Almost always this is a bad idea. Just because you can have three
variables with the same name but different sigils ($, @, %) doesn't
mean you should-- and most of the time it means you shouldn't.

@line really is a list of fields, so you should call it @fields
instead. And %line is presumably where you're storing your results,
so you might call it %name, or at the VERY least, %result.

Also, you only need @line inside the while loop, so you should declare
it there-- remember, we're not using C, where you have (had?) to
define all your variables at the start of a function; you can create
them wherever you need them.

(Actually, you don't need @line at all, but that can wait for a bit)
while ($line=<FILE>)
{
chomp($line);
@line = split(/\|/,$line);
}
close(FILE);

Let's see:

1) You don't need an explicit $line variable here, because

while(<$fh>) {

}

is morally equivalent to

while( defined($_ = <$fh>) ) {

}

And both chomp and split operate on $_ by default.

This would more preferentially look like:

while (<$userfile>) {
chomp;
my @fields = split /\|/;
$name{$fields[0]} = $fields[1];
}

Also, since this is a sub, presumably you want to return the hash you
just built:

return %name;

-=Eric
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top