Welcome, Guest! Registration

loc2log

Saturday, 2024-04-20
Main » 2015 » April » 08

Perl is full of neat one-liners. You can get string regex matches right into an array. It is best shown with example:

To make it interesting let's take some HTML-like markup:

$input='<name="Alice"/><name="Bob"/><name="Eve"/>';

and capture name attribute's values to an array:

@result = $input =~ /(?:\<name=\")(.+?)(?:\"\/>)/g;

As you see the actual capture happens in the middle of regex: "(.+?)", and /g forces the match to repeat over and over.

If we spice up the code with little bit of data dumping:

use Data::Dumper;
print Dumper(\@names);

we'll observe

$VAR1 = [
 'Alice',
 'Bob',
 'Eve'
 ];

Just as required :-)
Views: 639 | Added by: ep | Date: 2015-04-08 | Comments (0)