Perl search for string and get the full line from text file

perl

I want to search for a string and get the full line from a text file through Perl scripting.

So the text file will be like the following.

data-key-1,col-1.1,col-1.2
data-key-2,col-2.1,col-2.2
data-key-3,col-3.1,col-3.2

Here I want to apply data-key-1 as the search string and get the full line into a Perl variable.

Here I want the exact replacement of grep "data-key-1" data.csv in the shell.

Some syntax like the following worked while running in the console.

perl -wln -e 'print if /\bAPPLE\b/' your_file

But how can I place it in a script? With the perl keyword we can't put it into a script. Is there a way to avoid the loops?

Best Answer

If you'd know the command line options you are giving for your one-liner, you'd know exactly what to write inside your perl script. When you read a file, you need a loop. Choice of loop can yield different results performance wise. Using for loop to read a while is more expensive than using a while loop to read a file.

Your one-liner:

perl -wln -e 'print if /\bAPPLE\b/' your_file

is basically saying:

  • -w : Use warnings
  • -l : Chomp the newline character from each line before processing and place it back during printing.
  • -n : Create an implicit while(<>) { ... } loop to perform an action on each line
  • -e : Tell perl interpreter to execute the code that follows it.
  • print if /\bAPPLE\b/ to print entire line if line contains the word APPLE.

So to use the above inside a perl script, you'd do:

#!usr/bin/perl

use strict;
use warnings;

open my $fh, '<', 'your_file' or die "Cannot open file: $!\n";

while(<$fh>) {
    my $line = $_ if /\bAPPLE\b/;
    # do something with $line
}

chomp is not really required here because you are not doing anything with the line other then checking for an existence of a word.

Related Topic