PDA

View Full Version : Perl -- File manipulation (flat file databases)


sarah_anne
05-19-2003, 11:11 PM
sub ViewPublicProfile
{
$profile = $QUERY{'profile'};}


open(F,"users.dat") || die("Can't open file: $!");
while (<F>) {
($usernum, $rights, $active, $email, $firstname, $lastname, $password, $username) = split(/\s*\|\s*/);

ShowUserInfo();


}



As you can see from my fumbling attempts above, I'm trying to do something here that I've really got no idea how to go about.

I have a text file, with format as below:

firstname=James | lastname=Jones | age=13 | username=jj
firstname=Sarah | lastname=Smith | age=90 | username=sarah_smith
firstname=Tim | lastname=Nicebutdim | age=45 | username=tim_tim

... you get the picture.

All i'd like to do is, based in a little appendage to the URL of a perl script show that user's details.

So if a user typed in script.com/cgi-bin/script.cgi?profile=sarah_smith the profile details on Sarah Smith would be shown.

a) I don't know how to get perl to "select" the line it needs from the text file based upon this .cgi?profile=username thingy.

b) I don't know how to get perl to read the format of the data, where username=sarah_smith i'd only ever want sarah_smith to show, not the "username=" bit. Would I simply do a


$data =~ s/\username=/ /g;


Thanks for the help, anyone.... as you can see I've got some experience with perl but it's all higgeldy piggeldy and i'm kinda tying myself in knots in this steep learning curve :(

Sarah.

ACJavascript
05-20-2003, 05:18 PM
Hello Sarah,, Well you have the right idea. First you need to Parse the data,


Heres how I would pull the data,

----------

## Request Methods
if ($ENV{'REQUEST_METHOD'} eq 'GET') {
$query = $ENV{'QUERY_STRING'};
}else{
read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
}

@pairs = split(/&/, $buffer);
foreach $pair (@pairs) {
($name, $value) = split(/=/, $pair);
$value =~ tr/+/ /;
$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
$FORM{$name} = $value;
}
@values = split(/&/,$query);

if(@values[0] eq profile){
&Profile;
exit;
}else{
print "Not right query";


sub Profile {

$found=0;
open(F,"users.dat") || dia("Can't open file: $!");
@Data=<F>;
close(F);
chomp(@Data);
foreach $part(@Data){
($usernum, $rights, $active, $email, $firstname, $lastname, $password, $username) = split(/\|/,$part);

if(@values[1] eq $firstname){
$found=1;
}
}

if($found==1){
print "HELLO $firstname, $email, $rights, $lastname";
}else{
print "Sorry but we didn't find anyone by that name";
}

}

-------

I havn't tested it for small errors hehehe,, But thats a good way,, and for the link: ?profile=sarah instead of ?profile=sarah_smith because you would have to break apart sarah_smith to find there names.

If you need more help you are more then welcome to contact me ACJavascript@aol.com

Happy Scripting!