Search notes:

Perl matching: match and assign

use warnings;
use strict;

my $text = 'foo=40;bar=42;baz=44';

#                                                          prints
#                                                          --------+
my ($v1 ) = $text =~ /bar=(\d+);/;   print "v1: $v1\n";  # v1: 42  |    Note, $v1     within parantheses, g modifier NOT used
my  $v2   = $text =~ /bar=(\d+);/;   print "v2: $v2\n";  # v2: 1   |    Note, $v2 NOT within parantheses, g modifier NOT used
my ($v3 ) = $text =~ /bar=(\d+);/g;  print "v3: $v3\n";  # v3: 42  |    Note, $v3     within parantheses, g modifier     used
my  $v4   = $text =~ /bar=(\d+);/g;  print "v4: $v4\n";  # v4: 1   |    Note, $v4 NOT within parantheses, g modifier     used

print "----\n";

sub assign_if_matched_in_if_statement { # {{{

  my $string = shift;

  if (my ($matched) = $string =~ /^yes (.*)/) {
    print "String >$string< matched: $matched\n";
  }

} # }}}

assign_if_matched_in_if_statement('yes hello' );  #  prints «String >yes hello< matched: hello»
assign_if_matched_in_if_statement('no bye bye');  #  prints nothing


print "---\n";

my $another_string = "foo bar";

my ($matched) = $another_string =~ /baz (.*)/g;  # Returns undefined

if (defined $matched) {
  print "\$matched is defined\n";
}
else {
  print "\$matched is not defined\n";
}
Github repository about-perl, path: /functions/m__match_and_assign.pl

See also

Perl matching: Dynamic case sensitiveness
Perl functions

Index

Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 8 attempt to write a readonly database in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php:78 Stack trace: #0 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(78): PDOStatement->execute(Array) #1 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(30): insert_webrequest_('/notes/developm...', 1758207231, '216.73.216.150', 'Mozilla/5.0 App...', NULL) #2 /home/httpd/vhosts/renenyffenegger.ch/httpsdocs/notes/development/languages/Perl/functions/m__match_and_assign(80): insert_webrequest() #3 {main} thrown in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php on line 78