n0de
n0de

Reputation: 155

Perl File Reading Line By Line (RegEx)

What I am trying to do is open a file and read it line by line.
Once I found what my regex is looking for, I want to place each one into the @accounts array as well as print them onto my screen.

Though I'm not getting any result. I must be making a simple mistake here?

#!/usr/bin/perl

use strict;
use warnings;

my $line;
my $file;
my $start;
my $end;
my @match;
my @accounts;

print "Enter the file name (example: file.txt): ";
chomp ($file = <STDIN>);


open FILE, $file or die "Cannot open $file read :$!";

while ($line=<FILE>) {

    $start = '">';
    $end = '</option>';

    @match = ($line =~ /$start(.*?)$end/g);

    foreach (@match)
    {
        push @accounts, $_;
        print " $_\n ";
    }
}

Upvotes: 2

Views: 5746

Answers (2)

user846969
user846969

Reputation:

use feature ":5.16";
use warnings FATAL => qw(all);
use strict;

my $t = "aaaa\">AAAA</option>\n bbbb\">BBBB</option> cccc\">CCCC</option>";
my $start = '">';
my $end = '</option>';
say for $t =~ /$start(.*?)$end/g;

Produces:

AAAA
BBBB
CCCC

Upvotes: 0

7stud
7stud

Reputation: 48649

1) Don't use bareword filehandles:

open my $INFILE, '<', $fname
    or die "Couldn't open $fname: $!";

2) @match?? You used the g flag, so @matches would be a better name. Generally, array names are going to be plurals.

3) Avoid using $_ in your code:

for my $match (@matches) {
    print $match;
}

for and foreach are the same thing in perl, so use for--it's shorter to type.

4)

$start = '">';

Are you sure you want to look for a double quote followed by a > ?? Your code works fine for me with this data file:

<option">hello world</option>

However, that is some strange looking data.

Upvotes: 4

Related Questions