Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: Verify Town Name

by cavac (Parson)
on Nov 30, 2021 at 13:31 UTC ( [id://11139268]=note: print w/replies, xml ) Need Help??


in reply to Verify Town Name

First, this needs the format fixed. Strike that. This needs rewriting with functions. Let's see, hmmm, something like this should do the trick:

#!/usr/bin/env perl use strict; use warnings; use Carp; while(1) { my $town = getTown('towns.dat'); print "\nYou selected:\n"; print 'ID: ', $town->{id}, "\n"; print 'Short name: ', $town->{short}, "\n"; print 'Long name: ', $town->{long}, "\n"; print "\n"; } sub getTown { my ($fname) = @_; my $towns = loadFile($fname); while(1) { print "Select town: "; my $input = <>; chomp $input; if(defined($towns->{$input})) { return $towns->{$input}; } print "Unknown town!\n"; } } sub loadFile { my ($fname) = @_; open(my $ifh, '<', $fname) or croak($!); my %towns; while((my $line = <$ifh>)) { chomp $line; # Skip comments and empty lines next if($line eq '' || $line =~ /^\#/); print "# $line #\n"; my ($id, $short, $long) = split/\:/, $line; $towns{$short} = { id => $id, short => $short, long => $long, }; } close $ifh; return \%towns; }

Now, that is much easier to read and much easier to adapt. And it only loads the towns.dat file when you call getTown(). ANd you get back a hash with all info about the town that is available. But still, this could be a lot better. For once, we can decide to load the file only once per program run, reducing the number of file IO operations by trading in a bit of RAM. And while we are at it, let's add a spice of OO, so we can keep multiple data files in memory if we need to.

#!/usr/bin/env perl use strict; use warnings; use Carp; #use TownDatabase; my $towndb = TownDatabase->new(file => 'towns.dat'); while(1) { my $town = $towndb->get(); print "\nYou selected:\n"; print 'ID: ', $town->{id}, "\n"; print 'Short name: ', $town->{short}, "\n"; print 'Long name: ', $town->{long}, "\n"; print "\n"; } package TownDatabase; sub new { my ($proto, %config) = @_; my $class = ref($proto) || $proto; my $self = bless \%config, $class; $self->loadFile(); return $self; } sub get { my ($self) = @_; while(1) { print "Select town: "; my $input = <>; chomp $input; if(defined($self->{towns}->{$input})) { return $self->{towns}->{$input}; } print "Unknown town!\n"; } } sub loadFile { my ($self) = @_; open(my $ifh, '<', $self->{file}) or croak($!); my %towns; while((my $line = <$ifh>)) { chomp $line; # Skip comments and empty lines next if($line eq '' || $line =~ /^\#/); print "# $line #\n"; my ($id, $short, $long) = split/\:/, $line; $towns{$short} = { id => $id, short => $short, long => $long, }; } close $ifh; $self->{towns} = \%towns; }

Certainly not perfect, but now we could do something like this:

my $us_towndb = TownDatabase->new(file => 'towns_usa.dat'); my $eu_towndb = TownDatabase->new(file => 'towns_eu.dat');

Of course, with a little further rewrite, we can even add multiple files into a single memory class. Let's try this as well.

#!/usr/bin/env perl use strict; use warnings; use Carp; #use TownDatabase; my $towndb = TownDatabase->new(file => ['ustowns.dat', 'eutowns.dat']) +; while(1) { my $town = $towndb->get(); print "\nYou selected:\n"; print 'ID: ', $town->{id}, "\n"; print 'Short name: ', $town->{short}, "\n"; print 'Long name: ', $town->{long}, "\n"; print 'Source: ', $town->{source}, "\n"; print "\n"; } package TownDatabase; use strict; use warnings; use Carp; sub new { my ($proto, %config) = @_; my $class = ref($proto) || $proto; my $self = bless \%config, $class; $self->{towns} = {}; if(defined($self->{file})) { if(ref $self->{file} eq 'ARRAY') { foreach my $fname (@{$self->{file}}) { $self->loadFile($fname); } } else { $self->loadFile($self->{file}); } } return $self; } sub get { my ($self) = @_; while(1) { print "Select town: "; my $input = <>; chomp $input; if(defined($self->{towns}->{$input})) { return $self->{towns}->{$input}; } print "Unknown town!\n"; } } sub loadFile { my ($self, $fname) = @_; croak("File not found: $fname\n") unless(-f $fname); print "Loading file $fname...\n"; open(my $ifh, '<', $fname) or croak($!); my %towns; while((my $line = <$ifh>)) { chomp $line; # Skip comments and empty lines next if($line eq '' || $line =~ /^\#/); print "# $line #\n"; my ($id, $short, $long) = split/\:/, $line; $self->{towns}->{$short} = { id => $id, short => $short, long => $long, source => $fname, }; } close $ifh; }

Thanks to the more flexible filename handling in new() and loadFile(), we can even add files one-by-one instead of in the new() call:

my $towndb = TownDatabase->new(); foreach my $region (qw[eu us au]) { $towndb->loadFile($region . 'towns.dat'); }

Formatting your code properly, splitting it into functions and using OO where appropriate, it's much easier to follow, debug and enhance. It makes it also much easier to understand your question and find the problem. If you provide us with a bunch of badly formatted spaghetti code, helping you takes a lot more work - so fewer people will take the time and many will just glance at your post and move on to the next thing. So, please, for future questions, take the time to format the code and put it in a minimum viable running example. This will not only help you to read your own code better, it will also help us to help you to solve your problem.

So, that's my lunchbreak over, let's get back to building that pyramid for my boss. Oh man, those stones are heavy...

perl -e 'use Crypt::Digest::SHA256 qw[sha256_hex]; print substr(sha256_hex("the Answer To Life, The Universe And Everything"), 6, 2), "\n";'

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11139268]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (5)
As of 2024-04-25 04:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found