doubledecker
doubledecker

Reputation: 363

Processing data columns with Perl

i want to split the columns and get the data using the regex. looking for a simpler solution using backreferences.

previous balance payments adjustments charges payment without fine payment with fine

20,251.97 - 0.00 - 0.00 + 53,391.67 = 73,643.64 74,393.64

Here is the code

#!/usr/bin/perl
use strict;

my $regex = qr/^(\d|-)?(\d|,)*\.?\d*$/;
my $data = "20,251.97                   -          0.00              -           0.00              +         53,391.67            =         73,643.64                74,393.64"

Upvotes: 0

Views: 126

Answers (2)

Narveson
Narveson

Reputation: 1111

All your numbers seem to have a common format. You can write just one regex that works to capture any of your numbers. Then compose a longer regex that matches your records.

The benefit of this over the split method is that you can ask for a warning if your data doesn't match the format you expect.

my $num = qr{
    \s*          # skip whitespace
    (            # begin capture
        [\d,.]+  # comma, period, digits
    )            # end capture
    \s*          # skip whitespace
}x;

my (
    $prev_bal, $pmts_received, $adjustments, $charges, 
    $pmt_without_fine, $pmt_with_fine
) = $data =~ /$num \- $num \- $num \+ $num = $num $num/x
    or warn "Unexpected format: $data\n"; 

Upvotes: 0

Matt K
Matt K

Reputation: 13892

Why don't you just use the split function?

my @fields = split(/ +/, $data);

Upvotes: 8

Related Questions