maria maria - 4 months ago 26
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:

$t = 'cat Fruit.txt';

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


The proper way :


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 :


use strict; use warnings;

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

Usage :

./ 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);


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

Note the backticks