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:

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

Leave a Reply