The parenthesis serve two purposes: they can provide a grouping for a sub-expression[1], but they also create "capture groups", which are placed in numbered variables $1, $2, ..., or in the %+ hash if the new(ish) named capture groups feature is employed. But they also have the effect that when a regex is evaluated in list context, the capture groups are returned as a list.
Try this:
my $date = '2013-06-04 01:23:00'; # June 4th
$date =~ /^((\d{4})-(\d{2})-(\d{2})) ((..):(..):(..))$/;
The capture groups are numbered according to the order in which their opening paren is. Hence, the following would be true:
my $date = $1; # 2013-06-04
my $yyyy = $2; # 2013
my $mm = $3; # 06
my $dd = $4; # 04
my $time = $5; # 01:23
my $hh = $6; # 01
my $mm = $7; # 23
Similarly, in list context:
use Data::Dump;
my @a = $date =~ /^((\d{4})-(\d{2})-(\d{2})) ((..):(..):(..))$/;
dd @a;
__END__
("2013-06-04", 2013, "06", "04", "01:23:00", 23, "00")
Note that the array @a now contains the same values as $1..$7 at array positions 0..6
Hope this helps. As always, the Perl documentation is an excellent source of more detailed information: perlre and perlretut are good starting points.
[1] - If you are using parens for a sub-expression and do not require that expression to be captured into a $n capture variable (e.g., $color =~ /^(?:black|white|red|green|blue)$/), note I have used (?:...) in this example: this prevents the creation of a capture group, so the color would not be put into $1. This example is obviously contrived, but judicious use of (?:...) can result in performance improvements as well as increased clarity in your code. |