From: Rob Dixon <[email protected]>

To: [email protected]
Cc: Greg J <[email protected]>
Sent: Thu, January 27, 2011 11:38:07 AM
Subject: Re: Regex

On 27/01/2011 02:15, Greg J wrote:
> I am trying to extract numeric values from a data file and I'm having
> trouble writing a regular expression that would do this.
> 
> My data looks like this:<{5, 26}{20, 42, 64}{23, 48}>
> 
> I am trying to turn this into a list of lists [ [5, 26], [20, 42, 64],
> [23,48] ]
> 
> Any pointers would be greatly appreciated

Hi Greg

I am tempted to write

  my $data = '<{5, 26}{20, 42, 64}{23, 48}>';
  my $list = [ map { [ $_ =~ /\d+/g ] } $data =~ /(\{.*?\})/g ];

But the program below seems to do what you described more clearly :)

HTH,

Rob


use strict;
use warnings;

my $data = '<{5, 26}{20, 42, 64}{23, 48}>';

my $list;

while ($data =~ /(\{.*?\})/g) {
  my @sublist = $1 =~ /\d+/g;
  push @$list, \@sublist;
}

use Data::Dumper;
print Dumper $list;

**OUTPUT**

$VAR1 = [
          [
            '5',
            '26'
          ],
          [
            '20',
            '42',
            '64'
          ],
          [
            '23',
            '48'
          ]
        ];

-- To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/

Hi Rob, 

I refer to your 2 lines of code:

  my $data = '<{5, 26}{20, 42, 64}{23, 48}>';
  my $list = [ map { [ $_ =~ /\d+/g ] } $data =~ /(\{.*?\})/g ];

That's the type of Perl coding style I'm still trying to learn. Concise and 
elegant. Beautiful!!!
I am having a tough time to crack the secret of Perl's contexts. Any 
websites/books you could recommend which 

covers this area in depth and clearly?


      

Reply via email to