in reply to Re^4: Repeated Pattern Matching Fails
in thread Repeated Pattern Matching Fails
Another question that comes up all the time is about this $1 stuff and what a pain it is. So how to you avoid having to use $1? Use a list slice to assign $1 to a scalar without having to go via $1!use warnings; use strict; my $_sensor_type = 'I2600*&^_A8699()^%#@C9800&*%A96'; my @types = $_sensor_type =~ /[a-z]+([0-9]+)/ig; #parens aren't needed here but to make list clear, #could have been: #my @types = ($_sensor_type =~ /[a-z]+([0-9]+)/ig); print join("\n",@types),"\n"; __END__ ## prints ### 2600 8699 9800 96
There are lots of cases where this trick is handy. Some types of split scenarios can produce undef values and this special Perl operator ||= can override that to a value, like even "".my $_sensor_type = 'I2600*&^_A8699()^%#@C9800&*%A96'; my $type = ($_sensor_type =~ /[a-z]+([0-9]+)/i)[0]; print "$type\n"; #prints 2600 #so what happens if the match and consequent slice fails? $type ||= "some default"; #or check for undef
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^6: Repeated Pattern Matching Fails
by perlpal (Scribe) on Jan 29, 2009 at 05:15 UTC |