2 ms·
Not mentioned is the common idiom of assigning regexp matches. In perl, > my ($a, $b) = '12' =~ /(\d)(\d)/; In python, > (a, b) = re.match('(\d)(\d)', '12')
by tantalor 15y ago
Not mentioned is the common idiom of assigning regexp matches.
In perl,
> my ($a, $b) = '12' =~ /(\d)(\d)/;
In python,
> (a, b) = re.match('(\d)(\d)', '12').groups()
Note the python code here will throw an AttributeError if the match fails, whereas the perl will just assign undef to the variables.
- mst 15y agoActually, perl will return an empty list, which if then evaluated in scalar context will return 0, which is boolean false. So if (my ($x, $y) = '12' =~ /(\d)(\d)/) { <use $x and $y here> } is the normal idiom.
- joslin01 15y agoAlternatively, use named captures: > obj = re.match('(?P<id>\d\d)(?P<name>\w+)') > id = obj.group('id') > name = obj.group('name')
- Craiggybear 15y agoNice!