http://www.perlmonks.org?node_id=600537


in reply to Re: Rewrite for "How to get ($1, $2, ...)?
in thread How to get ($1, $2, ...)?

This is kinda a fun little challenge and so I played with it more. Below is a mix of several different solutions here, i know they probably wont help you but since i've worked it out and tested it some i figured i'd share:

use strict; use warnings; use Data::Dumper; my $test =<<HERE; Title: The Moor's Last Sigh Author: Salman Rushdie Publisher: Foo Title: The God of Small Things Author: Arundhati Roy Publisher: Bar Title: The Moor's Last Sigh, Author: Salman Rushdie HERE my @books = split /(?=Title:)/, $test; my @res = ( [ qr/^Title: (.*?), Author: (\w+) (\w+), Publisher: (\w+), Year: (\w ++)$/, sub { my $b = shift; $b->{title} = $1; $b->{author} = [$2,$3]; $b->{publisher} = $4; $b->{year} = $5; } ], [ qr/^Title: (.*?), Author: (\w+) (\w+), Publisher: (\w+)$/, sub { my $b = shift; $b->{title} = $1; $b->{author} = [$2,$3]; $b->{publisher} = $4 } ], [ qr/^Title: (.*?), Author: (\w+) (\w+)$/, + sub { my $b = shift; $b->{title} = $1; $b->{author} = [$2,$3] } ], [ qr/^Title: (.*?)$/, sub { my $b = shift; $b->{title} = $ +1; } ], [ qr/^Author: (\w+) (\w+)$/, sub { my $b = shift; $b->{author} = [ +$1,$2];}], [ qr/^Publisher: (.*?)$/, sub { my $b = shift; $b->{publisher}= $ +1; } ], ); my @answers; for my $book_src (@books) { my $book = {}; for my $re (@res) { my $reg = $re->[0]; if ($book_src =~ /$reg/mgc){ &{$re->[1]}($book); } } push @answers, $book; } print Dumper(\@answers); __END__ $VAR1 = [ { 'author' => [ 'Salman', 'Rushdie' ], 'title' => 'The Moor\'s Last Sigh', 'publisher' => 'Foo' }, { 'author' => [ 'Arundhati', 'Roy' ], 'title' => 'The God of Small Things', 'publisher' => 'Bar' }, { 'author' => [ 'Salman', 'Rushdie' ], 'title' => 'The Moor\'s Last Sigh' } ];

___________
Eric Hodges