Coincidir regex y asignar resultados en una sola línea de código
Quiero poder hacer una coincidencia de expresiones regulares en una variable y asignar los resultados a la propia variable. ¿Cuál es la mejor manera de hacerlo?
Quiero esencialmente combinar las líneas 2 y 3 en una sola línea de código:
$variable = "some string";
$variable =~ /(find something).*/;
$variable = $1;
¿Hay una forma más corta/simple de hacer esto? Me estoy perdiendo algo?
8 answers
¿por Qué quieres que sea más corto? ¿Es realmente importante?
$variable = $1 if $variable =~ /(find something).*/;
Si te preocupa el nombre de la variable o hacer esto repetidamente, envuelve la cosa en una subrutina y olvídalo:
some_sub( $variable, qr/pattern/ );
sub some_sub { $_[0] = $1 if eval { $_[0] =~ m/$_[1]/ }; $1 };
Sea cual sea su implementación, el objetivo de la subrutina es hacerla reutilizable para que le dé a un conjunto particular de líneas un nombre corto que ocupe su lugar.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-09-06 19:14:07
my($variable) = "some string" =~ /(e\s*str)/;
Esto funciona porque
Si la opción
/g
no se usa,m//
en el contexto de lista devuelve una lista que consiste en las subexpresiones coincidentes con los paréntesis en el patrón, i. e., ($1
,$2
,$3
...).
Y porque my($variable) = ...
(note los paréntesis alrededor del escalar) provee contexto de lista a la coincidencia.
Si el patrón no coincide, $variable
obtiene el valor indefinido.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-09-06 17:26:07
Puedes hacer la sustitución como:
$a = 'stackoverflow';
$a =~ s/(\w+)overflow/$1/;
$a
es ahora "stack"
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-29 17:34:11
Bueno, se podría decir
my $variable;
($variable) = ($variable = "find something soon") =~ /(find something).*/;
O
(my $variable = "find something soon") =~ s/^.*?(find something).*/$1/;
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-09-06 15:30:46
Casi ....
Puede combinar la coincidencia y recuperar el valor coincidente con una sustitución.
$variable =~ s/.*(find something).*/$1/;
AFAIK, siempre tendrá que copiar el valor, aunque, a menos que no le importe clobber el original.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-29 17:34:43
$variable2 = "stackoverflow";
(my $variable1) = ($variable2 =~ /stack(\w+)/);
$variable1
ahora es igual a "overflow"
.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-13 01:53:41
Hago esto:
#!/usr/bin/perl
$target = "n: 123";
my ($target) = $target =~ /n:\s*(\d+)/g;
print $target; # the var $target now is "123"
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-29 17:33:29
De Perl Cookbook 2nd ed 6.1 Copiar y Sustituir Simultáneamente
$dst = $src;
$dst =~ s/this/that/;
Se convierte en
($dst = $src) =~ s/this/that/;
Asumí que todo el mundo lo hacía de esta manera, asombrado de que nadie diera esta respuesta.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-11 20:22:34