René Nyffenegger's collection of things on the web
René Nyffenegger on Oracle - Most wanted - Feedback -
 

Substitution and matching in Perl

Substitution and assignment in one line

use warnings;
use strict;

my $orig="Here's the number: 42.";

(my $num = $orig) =~ s/\D*(\d+)\D*/I have found: $1/;

print "$orig\n";
print "$num\n";
Output:
Here's the number: 42.
I have found: 42

Substitution with a function call

use warnings;
use strict;

sub plus {
  my $a = shift;
  my $b = shift;

  return $a+$b;
}

my $foo = "forty-two plus five is 42+5 while ten plus twenty is 10+20, hopefully.";

$foo =~ s!(\d+) *\+ *(\d+)!plus($1, $2)!eg;

print $foo;
This prints:
forty-two plus five is 47 while ten plus twenty is 30, hopefully.

Matching

use warnings;
use strict;

my $string_1 = "foo bar baz";
my $string_2 = "foo 42 bar 43 baz";

print "Match String 1 without parantheses: ", $string_1 =~  /\d+/  , "\n";
print "Match String 2 without parantheses: ", $string_2 =~  /\d+/  , "\n";
print "Match String 1 with    parantheses: ", $string_1 =~ /(\d+)/ , "\n";
print "Match String 2 with    parantheses: ", $string_2 =~ /(\d+)/ , "\n";
Match String 1 without parantheses:
Match String 2 without parantheses: 1
Match String 1 with    parantheses:
Match String 2 with    parantheses: 42
use warnings;
use strict;

my $string_1 = "foo 42 bar 43 baz";
my $string_2 = "foo 42 bar 43 baz";
my $string_3 = "foo 42 bar 43 baz";

my $result_1 = $string_1 =~  /\d+/g;
my $result_2 = $string_2 =~ /(\d+)/g;
my @result_3 = $string_3 =~ /(\d+)/g;

print "1: $result_1\n";
print "2: $result_2\n";
print "3: ", (join "-", @result_3), "\n";
1: 1
2: 1
3: 42-43
use warnings;
use strict;

my $string_1 = "foo 42 bar 43 baz";
my $string_2 = "foo 42 bar 43 baz";
my $string_3 = "foo 42 bar 43 baz";

my $result_1 = $string_1 =~  /\d+/g;
my $result_2 = $string_2 =~ /(\d+)/g;
my @result_3 = $string_3 =~ /(\d+)/g;

print "1: $result_1\n";
print "2: $result_2\n";
print "3: ", (join "-", @result_3), "\n";
42
changed