user717236 user717236 - 5 months ago 18
Perl Question

Extract text and write to a new file in Perl

Simply put, I want to extract text from a file and save that text to a new file, using Perl.

Here is my code, thus far:

#!/usr/local/bin/perl

use warnings;
use strict;
use File::Slurp;
use FileHandle;

use Fcntl qw(:DEFAULT :flock :seek); # Import LOCK_* constants

my $F_IN = FileHandle->new("<$ARGV[0]");
my $F_OUT = FileHandle->new(">PerlTest.txt");

while (my $line = $F_IN->getline) {
$line =~ m|foobar|g;
$F_OUT->print($line);
# I want to only copy the text that matches, not the whole line.
# I changed the example text to 'foobar' to avoid confusion.
}

$F_IN->close();
$F_OUT->close();


Obviously, it's copying the line. How can I extract and print specific text from a file, instead of the whole line?

Answer

You could use capturing parentheses to grab the matched string:

while (my $line = $F_IN->getline) {
    if ($line =~ m|(thebigredpillow)|) {
        $F_OUT->print("$1\n");
    }
}

See perldoc perlre.

Comments