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.
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";'
|