So (\([^\n]+\)) is optional? Then let's add a ? as follows:'ab' =~ /a(z?)b/ # Returns ''. 'ab' =~ /a(z)?b/ # Returns undef.
my @fizzbin = ( $string =~ m{ (\w+)\n # Grab the title What:\s+([^\n]+)\n # Grab the what Date\sadded:\s+([^\(^\n]+) # Date added (\([^\n]+\))?\n # Optional source Data:\s+([^\n]+)\n # Grab the data }xmgs);
After looking at my first snippet, we determine that the source will be undef if the source is omitted. Let's rearrange your code to use named variables like you wanted, and let's integrate the default. We get the following:
while ( my ($title, $what, $date, $source, $data) = $string =~ m{ (\w+)\n # Grab the title What:\s+([^\n]+)\n # Grab the what Date\sadded:\s+([^\(^\n]+) # Date added (\([^\n]+\))?\n # Optional source Data:\s+([^\n]+)\n # Grab the data }xmgs ) { $source = '' if not defined $source; # Use default ''. ... }
By the way,
In reply to Re: Default value for capture in regular expression
by ikegami
in thread Default value for capture in regular expression
by redhotpenguin
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |