maria maria - 1 month ago 10
Perl Question

extracting data from a file using perl

Using Perl in Shell script, I am trying to extract word "apple" from a text file called "Fruit.txt"(The file holds name of different fruits)

For that I created a created a script as follow:

#!/usr/bin/perl
$t = 'cat Fruit.txt';


How can I now extract substring (in this case apple) from this file using grep - o. Thank you

Answer

The proper way :

#!/usr/bin/perl

use strict; use warnings;

my $fic = './Fruit.txt';

open my $fh, "<", $fic
    or die("An error hapenned opening file\n");

while (<$fh>) {
    print if /Apple/i;
}

close $fic;

Or :

#!/usr/bin/perl

use strict; use warnings;

while (<>) {
    print if /Apple/i;
}

Usage :

./script.pl Fruits.txt

Or the concise way:

perl -ne 'print if /whatever/' file

The bad way (non portable) that you seems to try :

my $file = qx(cat Fruits.txt);

or

my $file = `cat Fruits.txt`;
           ~              ~

Note the backticks