tags:

views:

65

answers:

3
@temp = split(/\./, $_);
$val = $temp[1];
$val =~ s/\D//;

What is the correct syntax to write a single statement instead of these three statements in 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.

+6  A: 

A list slice looks like (LIST)[LIST]; you've omitted the () part.

($val = (split(/\./, $_))[1]) =~ s/\D//;
ysth
+3  A: 

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";
Kinopiko
Yes, I meant to remove all the non digits from the string (`/g` dos the job).
Lazer
+12  A: 

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.

Philip Potter
+1 for the "Don't do it" after showing how to anyway.
Jonathan Leffler
@Jonathan: quite. good programmers should know the bad uses of a language, and why not to use them. So we must teach learners bad examples as well as good.
Philip Potter