Main » 2015 » April » 8 » Perl store regex matches to array
0:13 AM Perl store regex matches to array |
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' ]; |
|
Total comments: 0 | |