Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Verify Town Name

by PilotinControl (Pilgrim)
on Nov 30, 2021 at 00:34 UTC ( #11139256=perlquestion: print w/replies, xml ) Need Help??

PilotinControl has asked for the wisdom of the Perl Monks concerning the following question:

Hello Fellow Monks!
I have a perplexing issue with my code below. I am trying to verify a town name located in a file using it as a check and balance before moving on to the next user input. However no matter what is inputted it moves on with out giving notice stating the town name has not been found. Thanks in advance!

sub addind { open(MYINPUTFILE, "townsdata.txt"); # OPEN FOR INPUT $| = 1; my @lines = <MYINPUTFILE>; # READ FILE INTO LIST print "INDUSTRY TOWN\n"; my $indtwn = <STDIN>; $indtwn = <STDIN> until defined $indtwn; chomp $indtwn; cls(); my $found = 0; foreach my $townverify (@lines) { my @field = split(':',$townverify); if ($field[0] =~ m/^#/) { next; } if ($field[1] =~ /(?<![\w-])$indtwn(?![\w-])/i) { cls(); $found = 1; } else { cls(); print "TOWN RECORD NOT FOUND\n"; sleep 3; cls(); addind(); } # END FOREACH FILE LOOP my $output="inddata.txt"; open(DAT,"+<$output") || die("Cannot Open File"); my $indline; $indline = <DAT> until eof DAT; my ($indid) = $indline =~ m/\A(\d+):/; print DAT (++$indid); print DAT (":"); print DAT ($indtwn); print DAT ("\n"); close (DAT); print "INDUSTRY SUCCESSFULLY ADDED!!\n"; sleep 3; cls(); industry(); }
Data:
1:PGH:Pittsburgh
2:PGHW:Pittsburgh West End

Replies are listed 'Best First'.
Re: Verify Town Name
by Discipulus (Abbot) on Nov 30, 2021 at 07:47 UTC
    Hello PilotinControl,

    help us to help you giving runnable and correctly indented code :)

    Your perLplexing issue can arise from wrong index 1 (instead of 2) in $field[1] ? Use Data::Dump here and there to verify data you are processing.

    The following works as expected

    use strict; use warnings; my @lines = <DATA>; @lines = map {chomp $_; $_} @lines; my $indtwn = <STDIN>; # $indtwn = <STDIN> until defined $indtwn; ??? chomp $indtwn; my $found = 0; foreach my $townverify (@lines) { my @field = split(':',$townverify); next if $field[0] =~ m/^#/; if ( $field[2] eq $indtwn ){ # <--- here print "FOUND $indtwn\n"; $found++; last; } } print "[$indtwn] NOT FOUND" unless $found; __DATA__ 1:PGH:Pittsburgh 2:PGHW:Pittsburgh West End

    L*

    There are no rules, there are no thumbs..
    Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.

      Time vampires will never "help us to help you giving runnable and correctly indented code :)."


      Dave

      Thank You @Discipulos your code worked. Now I need to compare the Industry from another file whether it exists or not. Same type of foreach loop. If it exists it moves on if not it circles back to itself. Would this be considered a nested foreach loop? My current working code to find Town Name is below. Would I add another foreach loop below the current one? I need to save the variables from each user input and send it to a file which I already have coded. Thanks for the help!

      #!/usr/bin/perl -w use strict; use warnings; begin(); sub begin { open(MYINPUTFILE, "towndata.txt") or die $!; # OPEN FOR INPUT $| = 1; my @lines = <MYINPUTFILE>; # READ FILE INTO LIST @lines = map {chomp $_; $_} @lines; close (MYINPUTFILE); print "LOCATION TOWN:\n"; my $loctwn = <STDIN>; $loctwn = <STDIN> until defined $loctwn; chomp $loctwn; my $found = 0; foreach my $loctownverify (@lines) { my @field = split(':',$loctownverify); if ( $field[1] eq $loctwn ){ print "FOUND $loctwn\n"; $found++; sleep 1; print "INDUSTRY NAME:\n"; my $locindstanm = <STDIN>; $locindstanm = <STDIN> until defined $locindstanm; chomp $locindstanm; print "LOCATION SUCCESSFULLY ADDED!!\n"; sleep 3; exit; } # END IF } # END FOR EACH LOOP print "[$loctwn] RECORD NOT FOUND\n", unless $found; sleep 3; begin(); } # END BEGIN SUB
      UPDATE
      I have figured out how to check two items....now I'm stumped on how to go back to the second verification if an item does not exist.
      #!/usr/bin/perl -w use strict; use warnings; begin(); sub begin { no warnings 'redefine'; no warnings 'uninitialized'; my $found = 0; my $foundtwo = 0; open(MYINPUTFILE, "towndata.txt") or die $!; # OPEN FOR INPUT open(MYINPUTFILETWO, "industrydata.txt") or die $!; # OPEN FOR INPUT $| = 1; my @lines = <MYINPUTFILE>; # READ FILE INTO LIST my @linestwo = <MYINPUTFILETWO>; # READ FILE INTO LIST @lines = map {chomp $_; $_} @lines; @linestwo = map {chomp $_; $_} @linestwo; close (MYINPUTFILE); close (MYINPUTFILETWO); print "LOCATION TOWN:\n"; my $loctwn = <STDIN>; $loctwn = <STDIN> until defined $loctwn; chomp $loctwn; foreach my $loctownverify (@lines) { my @field = split(':',$loctownverify); if ( $field[1] eq $loctwn ){ print "FOUND $loctwn\n"; $found++; sleep 1; print "INDUSTRY NAME:\n"; my $locindstanm = <STDIN>; $locindstanm = <STDIN> until defined $locindstanm; chomp $locindstanm; foreach my $locindstaverify (@linestwo) { my @fieldtwo = split(':',$locindstaverify); if ( $fieldtwo[2] eq $locindstanm ){ print "FOUND $locindstanm\n"; $foundtwo++; sleep 1; print "LOCATION SUCCESSFULLY ADDED!!\n"; my $output="locindstadata.txt"; open(DAT,"+<$output") || die("Cannot Open File"); # NEW my $locindstaline; $locindstaline = <DAT> until eof DAT; my ($locindstaid) = $locindstaline =~ m/\A(\d+):/; print DAT (++$locindstaid); print DAT (":"); print DAT ($loctwn); print DAT (":"); print DAT ($locindstanm); print DAT ("\n"); close (DAT); sleep 3; exit; } # END IF } # END FOR EACH LOOP print "[$locindstanm] RECORD NOT FOUND\n", unless $foundtwo; } } print "[$loctwn] RECORD NOT FOUND\n", unless $found; sleep 3; begin(); } # END BEGIN SUB

Re: Verify Town Name
by Anonymous Monk on Nov 30, 2021 at 07:47 UTC
    However no matter what is inputted it moves on with out giving notice stating the town name has not been found.

    SSCCE, perltidy, and the code "works"...

    use warnings; use strict; addind(); sub addind { open( MYINPUTFILE, "townsdata.txt" ) or die $!; $| = 1; my @lines = <MYINPUTFILE>; print "INDUSTRY TOWN\n"; my $indtwn = <STDIN>; $indtwn = <STDIN> until defined $indtwn; chomp $indtwn; print "cls();\n"; my $found = 0; foreach my $townverify (@lines) { my @field = split( ':', $townverify ); if ( $field[0] =~ m/^#/ ) { next; } if ( $field[1] =~ /(?<![\w-])$indtwn(?![\w-])/i ) { print "cls();\n"; $found = 1; } else { print "cls();\n"; print "TOWN RECORD NOT FOUND\n"; print "sleep 3;\n"; print "cls();\n"; addind(); } my $output = "inddata.txt"; open( DAT, "+<$output" ) || die("Cannot Open File"); my $indline; $indline = <DAT> until eof DAT; my ($indid) = $indline =~ m/\A(\d+):/; print DAT ( ++$indid ); print DAT (":"); print DAT ($indtwn); print DAT ("\n"); close(DAT); print "INDUSTRY SUCCESSFULLY ADDED!!\n"; print "sleep 3;\n"; print "cls();\n"; print "industry();\n"; } }
    $ perl 11139256.pl
    INDUSTRY TOWN
    Foo
    cls();
    cls();
    TOWN RECORD NOT FOUND
    sleep 3;
    cls();
    INDUSTRY TOWN
    PGH
    cls();
    cls();
    INDUSTRY SUCCESSFULLY ADDED!!
    sleep 3;
    cls();
    industry();
    cls();
    TOWN RECORD NOT FOUND
    sleep 3;
    cls();
    INDUSTRY TOWN
    ^C
    
Re: Verify Town Name
by cavac (Priest) on Nov 30, 2021 at 13:31 UTC

    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";'
Re: Verify Town Name
by vincent_veyron (Sexton) on Dec 04, 2021 at 23:07 UTC

    I suppose you can't do anything about it, but all your problems would be solved so easily with a foreign key constraint in a relational database, it makes me want to cry...

    https://compta.libremen.com

    Logiciel libre de comptabilité générale en partie double

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://11139256]
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (6)
As of 2022-05-25 11:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you prefer to work remotely?



    Results (90 votes). Check out past polls.

    Notices?