Write a perl script, searchtwo.pl, that will search a given data file for a given pattern. Both the search pattern and the search file name should be obtained from the prompted inputs as the examples shown below (Lab 9 questions 4 and 5):
$ ./searchtwo.pl
Enter a data file name: /etc/services
Enter a search pattern: pop
$ ./searchtwo.pl
Enter a data file name: /etc/services
Enter a search pattern: imap
You might want to review Example 5 in Lab 8 and Examples 2.1 to 2.3 in Lab 9 before writing up your script sesearchtwo.pl;
Please test your script to make sure it displays the same information as you used grep for the two search patterns and the file in Lab 9
Perl script named searchtwo.pl that prompts the user for a data file
Certainly! Below is a Perl script named searchtwo.pl that prompts the user for a data file name and a search pattern. It then searches the specified file for the given pattern and prints all matching lines, similar to the behavior of the grep command.
Perl Script: searchtwo.pl
#!/usr/bin/perl
use strict;
use warnings;
# Prompt user for the data file name
print "Enter a data file name: ";
my $file_name = ;
chomp($file_name); # Remove newline character
# Prompt user for the search pattern
print "Enter a search pattern: ";
my $search_pattern = ;
chomp($search_pattern); # Remove newline character
# Check if the file exists
if (!-e $file_name) {
die "File '$file_name' does not exist.\n";
}
# Open the file for reading
open(my $fh, '<', $file_name) or die "Could not open file '$file_name': $!\n";
# Initialize a line counter
my $line_number = 0;
# Search through each line of the file
while (my $line = <$fh>) {
$line_number++;
# Check if the line matches the search pattern
if ($line =~ /$search_pattern/) {
print "Line $line_number: $line"; # Print the matching line with its number
}
}
# Close the file handle
close($fh);
Instructions to Use the Script
1. Save the Script: Copy the above code into a text editor and save it as searchtwo.pl.
2. Make it Executable: Before running the script, ensure it has executable permissions. You can do this with the following command:
chmod +x searchtwo.pl
3. Run the Script: Execute the script in your terminal:
./searchtwo.pl
4. Input Prompts: The script will prompt you to enter a data file name and a search pattern. For example:
Enter a data file name: /etc/services
Enter a search pattern: pop
5. View Results: The script will display lines from the specified file that match the search pattern along with their line numbers.
Example Usage
If you test the script with:
./searchtwo.pl
And input:
Enter a data file name: /etc/services
Enter a search pattern: pop
You would see similar results as you would with:
grep pop /etc/services
Important Notes:
- The search pattern is treated as a regular expression, so you can use regex syntax in your patterns.
- This script uses basic error handling to check if the specified file exists before attempting to read it.