Adrian
Adrian

Reputation: 9803

Perl: using regular expression to find patterns in a file

print "enter file name\n";
open (INFO, <>);
while ($line = <INFO>){
  if ($line =~ m/(\d+)/) {
  print "$1 \n";
  }
}

I want to find any digits in my file and print them on separate lines. However, if my file contains something like:

Hi there 45661 apples bananas 3 yes no maybe 11111

Then my program only prints out 45661 and nothing else. How can I get it to print out

456661
3
1111

Upvotes: 1

Views: 39

Answers (1)

Miller
Miller

Reputation: 35208

You need to put your regex in a while loop with the /g modifier:

print "enter file name\n";
chomp( my $filename = <STDIN> );

open my $fh, '<', $filename or die "Can't open $filename: $!";

while ( my $line = <$fh> ) {
    while ( $line =~ /(\d+)/g ) {
        print "$1\n";
    }
}

Upvotes: 1

Related Questions