user717236 user717236 - 1 year ago 80
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:


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;
# I want to only copy the text that matches, not the whole line.
# I changed the example text to 'foobar' to avoid confusion.


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

Answer Source

You could use capturing parentheses to grab the matched string:

while (my $line = $F_IN->getline) {
    if ($line =~ m|(thebigredpillow)|) {

See perldoc perlre.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download