Cenobite has asked for the wisdom of the Perl Monks concerning the following question:
I'm still a Perl newb, but am having lots of fun learning. I've created a few projects for myself, just as exercises, but I find myself stuck at the following one.
Basically, the script will accept two commands: "!read" and "!write", with proper arguments, and get or set the email address for a specific username (check out the code comments for details). It will read the information from (or save it to) an external file.
dbhandler is the subroutine that I'd like to handle the actual reading and writing.
Anyway, the code below is as far as I've gotten. I'm really stuck. Among other things, I'm not too sure what the most efficient way is to scan the file for the correct entry, nor how to update an existing entry. Oh yes, and commands must be case-insensitive, so "!READ John" and "!read john" should be the same.
#!/usr/bin/perl -w # "!read username" will read username's e-mail address. # "!write username user@example.com" will set username's e-mail addres +s # to user@example.com. # # Commands must be handled case-insensitively. use strict; print ("Hello there, what would you like to do? "); my $input_command = <STDIN>; chomp ($input_command); # Break $input_command into a space-delimited array and assign only th +e # first element (which will be the command) to $command. my $command = (split /\s/, $input_command)[0]; $command =~ tr/A-Z/a-z/; # lowercase everything # Take the second element (the name) and assign it to $name my $name = (split /\s/, $input_command)[1]; # Take the third element and assign it to $address my $address = (split /\s/, $input_command)[2]; if ($command =~ /!read\b/ || $command =~ /!write\b/) { print ("The command you entered is $command\n"); if ($name) { print ("The name you entered is $name\n"); } if ($address) { print ("The address you entered is $address\n"); } dbhandler($command, $name, $address); } else { print ("Sorry, only !read and !write are valid commands.\n"); } sub dbhandler { my ($subcommand, $subname, $subaddress) = @_; # lowercase everything. $subcommand is already received lowercase $subname =~ tr/A-Z/a-z/; $subaddress =~ tr/A-Z/a-z/; if ($subcommand =~ /!read\b/ { open ADDYFILE, "addyfile" || die "Couldn't open file: $!"; # rest of the subroutine should go here
Any hints, advice (and code! :)) would be appreciated.
Thanks!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Read from and write to file
by wojtyk (Friar) on Apr 05, 2007 at 20:09 UTC | |
by Cenobite (Novice) on Apr 05, 2007 at 20:47 UTC | |
by TStanley (Canon) on Apr 05, 2007 at 22:33 UTC | |
by Cenobite (Novice) on Apr 05, 2007 at 22:38 UTC | |
|
Re: Read from and write to file
by jethro (Monsignor) on Apr 05, 2007 at 22:40 UTC | |
by Anonymous Monk on Apr 09, 2007 at 17:19 UTC |