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