Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reading from a File Based on a String Input

I’m writing a program currently in Perl, and what I want it to do is take the user’s input (a string in my case), read a file, find an entry in the file with that input, and then print.

This is what I have so far in this particular subroutine where this bit of code is:

print "What is your Sun Sign?\n";
  
    open ( my $sun, '<', 'sunsigns.txt' )or die "I couldn't reach the file. Please try again.";
    
    while (my $sun_out = <STDIN>){

        if ($sun_out =~ /[\w$sun]/){
            print $sun;
        }

    }

When I do that, it gives me this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

GLOB(0x1db5f8)

I’m at my limit. I feel like I’ve literally tried everything that I’ve managed to Google. If anyone could at least point me in the right direction, please do.

>Solution :

Here is a common way to do this in Perl.

First, get the input string from STDIN.

Then, open the input file and loop over all lines looking for the input string. When you find the string, print the full line containing the string.

use warnings;
use strict;

print "What is your Sun Sign?\n";
my $sun = <STDIN>;
chomp $sun;

open (my $fh, '<', 'sunsigns.txt') or die "I couldn't reach the file. Please try again.";
while (<$fh>) {
    if (/$sun/) {
        print;
    }
}

See also perlintro

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading