Regular expression to get a number on a line

Viewed 126

I have to add some easy lines to Perl, and I don't exactly get the regular expressions and how I have to use it. I run a file and get the input from there:

open myFile, "csh ........

I run over the lines of the file output by doing "print", and I see one of the lines is:

TaskID:             1000

(there are plenty of spaces there). What I want to do, is simply to identify the case were the line begins with TaskID: and then get the number into a variable.

In order to identify the line which begins with TaskID, I did:

if (/TaskID:/) {

my questions:

  1. The if condition works and it does find when it is the line starts with TaskID. But is it the correct way to do it, or is there something better?
  2. I don't get how to get the number in this line into a variable.

I tried something like:

my $mytask = $1;

But, it doesn't get it. Can you help me understand how to get the number?

3 Answers

$1 contains the text matched by the first capture ((...)). Your pattern has no captures, and thus doesn't set $1. Fixed:

if (/^TaskID:\s*(\d+)/) {
   my $task_id = $1;
   ...
}

But I like to avoid using $1.

if ( my ($task_id) = /^TaskID:\s*(\d+)/ ) {
   ...
}

Well, it is a simple filtering task which can be solved with following code

NOTE: run as ./script.pl data_file

  • while creates a loop over the file
  • <> reads from a file provided as an argument to the script
  • regular expression selects a piece of interest
  • say $1 prints captured data to a screen
use strict;
use warnings;
use feature 'say';

/^TaskID:\s+(\d+)/ && say $1 while <>;

You can use \s+ to match multiple whitespaces and (\d+) to match and capture the digits. Refer to perldoc perlre. Here is a self-contained example:

use warnings;
use strict;

while (<DATA>) {
    if (/^TaskID:\s+(\d+)/) {
        my $task = $1;
        print "$task\n";
    }
}

__DATA__
TaskID:             1000
stuff
TaskID:             700
junk

This prints:

1000
700
Related