user3649361
user3649361

Reputation: 954

Regular expression in Perl not giving expected answer

I am trying to implement a regular expression in Perl. My code is

my $version=6.1; 
$version =~ /\d./;
print $version;

Expected output:

6.

or

6

Current output:

6.1

I tried the above method in regxpal and regxr where it is giving me 6.. However, I get 6.1.

I also tried:

$version =~ /\d\./;

What is wrong with it?

Upvotes: 2

Views: 63

Answers (5)

Borodin
Borodin

Reputation: 126762

What I imagine you want is to remove any fractional part of a numeric string

This will do that

my $version = 6.1; 
$version =~ s/\..*//;
print $version, "\n";

output

6

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174844

You may trim all the chars except \d\.

my $version = 6.1; 
$version =~ s/.*(\d\.).*/$1/;
print $version;

Now, it would print 6.. What you do in the code is, you just do matching only.

IDEONE

To get only the digit which exists before dot.

$version =~ s/.*(\d)\..*/\1/;

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627468

All you need to do to make your regex work is using $& backreference, and to match a literal dot, you need to escape it or put in a character class:

print "$&";

See IDEONE:

my $version=6.1; 
$version =~ /\d\./;
print "$&";  # => 6.

See perldoc.perl.org:

Even if there are no groupings in a regexp, it is still possible to find out what exactly matched in a string. If you use them, Perl will set $` to the part of the string before the match, will set $& to the part of the string that matched, and will set $' to the part of the string after the match.

Upvotes: 1

alisea
alisea

Reputation: 362

You can also directly assign the content of $1 back to $version, like this:

my $version = 6.1;
( $version ) = $version =~ /(\d\.)/;
print $version;

This can be extended if you want to capture several groups as well:

my ($main_version, $minor_version ) = $version =~ /(\d)\.(\d)/;

Upvotes: 3

Tom Fenech
Tom Fenech

Reputation: 74695

Just capture the part you're interested in using parentheses, then it will be assigned to $1:

my $version = 6.1;
$version =~ /(\d\.)/;
print $1;

Output:

6.

To overwrite the original variable, you could go with something like this:

my $version = 6.1;
if ($version =~ /(\d\.)/) {
    $version = $1;
}

This will only overwrite the variable if the pattern is matched.

Upvotes: 1

Related Questions