@temp = split(/\./, $_);
$val = $temp[1];
$val =~ s/\D//;
What is the correct syntax to write a single statement instead of these three statements in开发者_StackOverflow Perl?
($val = split(/\./, $_)[1]) =~ s/\D//;
gives me
syntax error at test.pl line 126, near ")["
Execution of test.pl aborted due to compilation errors.
Here's how:
$_="ab123.ab456cd.78";
($val = (split(/\./))[1])=~ s/\D//g;
print $val;
(I took the liberty of using the implicit $_
in split
, and adding the /g
tag to the s///
because removing one non-digit from the front didn't make much sense.)
Now you know this, don't do it. It's not clear to read, it doesn't show your intensions, and it's horrible. Much clearer is:
$val = (split /\./)[1];
$val =~ s/\D//g;
Code isn't just written for the computer. It's written for people to read in order that they can later modify it. If you don't write nice code for the next guy (who could be you in 2 months time), the next guy will have a horrible time figuring out what you did.
A list slice looks like (LIST)[LIST]
; you've omitted the ()
part.
($val = (split(/\./, $_))[1]) =~ s/\D//;
Here it is:
(my $val = (split /\./)[1]) =~ s/\D//;
Did you mean \D+
, by any chance?
Test:
#!perl
use warnings;
use strict;
$_ = "22.99grams";
(my $val = (split /\./)[1]) =~ s/\D+//;
print "$val\n";
精彩评论