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.
CodePudding user response:
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
CodePudding user response:
Given this file:
$ cat file
♈ Aries (Ram): March 21–April 19.
♉ Taurus (Bull): April 20–May 20.
♊ Gemini (Twins): May 21–June 21.
♋ Cancer (Crab): June 22–July 22.
♌ Leo (Lion): July 23–August 22.
♍ Virgo (Virgin): August 23–September 22.
♎ Libra (Balance): September 23–October 23.
♏ Scorpius (Scorpion): October 24–November 21.
You can do something like this:
#!/usr/bin/perl
use strict; use warnings;
print "Enter Sun Sign: ";
my $sign = <STDIN>;
chomp $sign;
open ( my $sun, '<', '/tmp/file' )or die "I couldn't reach the file. Please try again.";
while (my $line=<$sun>) {
chomp $line;
print $line if ($line=~/\b$sign\b/);
}
Test it:
Enter Sun Sign: Virgo
♍ Virgo (Virgin): August 23–September 22.