Search code examples
perl

Perl Search for string and print out line


I want to write a perl script that ask the user for a string and then finds the lines that contains that string and prints them. This is what i have so far

#!/usr/bin/perl

use strict;
use warnings;

sub main
{
    print "First name or Last Name or any portion: ";
    my $name = <STDIN>;
    my $file = '/home/jake/Downloads/phones';
    open(FH, $file) or die("File $file not found");
     
    while(my $String = <FH>)
    {
        if($String =~ $name)
        {
            print "$String \n";
        }
    }
    close(FH);
}
main();

Whenever I try this the terminal doesnt print anything. Is there anything that I could do to fix that?


Solution

  • Try this out:

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    sub main
    {
        print "First name or Last Name or any portion: ";
        my $name = <STDIN>; 
        chomp $name;
        my $file = '/home/jake/Downloads/phones';
        open my $fh, '<', $file or die "$file: $!\n";
    
        while(my $string = <$fh>)
        {
            if($string =~ /$name/)
            {
                print "$string\n";
            }
        }
        close($fh);
    }
    main();
    
    • You need to omit the new line character using chomp.
    • Use a modern way to read a file, using a lexical filehandle.