Search code examples
regexperl

How do you assign a variable to a regex match result


How do you create a $scalar from the result of a regex match? Is there any way that once the script has matched the regex that it can be assigned to a variable so it can be used later on, outside of the block. IE. If $regex_result = blah blah then do something. I understand that I should make the regex as non-greedy as possible.

#!/usr/bin/perl
use strict;
use warnings;
# use diagnostics;
use Win32::OLE;
use Win32::OLE::Const 'Microsoft Outlook';
my @Qmail;

my $regex = "^\\s\*owner \#";
my $sentence = $regex =~ "/^\\s\*owner \#/";

my $outlook = Win32::OLE->new('Outlook.Application')
    or warn "Failed Opening Outlook.";
my $namespace = $outlook->GetNamespace("MAPI");
my $folder    = $namespace->Folders("test")->Folders("Inbox");
my $items     = $folder->Items;

foreach my $msg ( $items->in ) {
    if ( $msg->{Subject} =~ m/^(.*test alert) / ) {
        my $name = $1;
        print "  processing Email for $name \n";
        push @Qmail, $msg->{Body};
    }
}

for(@Qmail) {
  next unless /$regex|^\s*description/i;
  print; # prints what i want ie lines that start with owner and description
}

print $sentence; # prints ^\\s\*offense \ # not lines that start with owner.

Solution

  • Use Below Perl variables to meet your requirements -

    $` = The string preceding whatever was matched by the last pattern match, not counting patterns matched in nested blocks that have been exited already.

    $& = Contains the string matched by the last pattern match

    $' = The string following whatever was matched by the last pattern match, not counting patterns matched in nested blockes that have been exited already. For example:

    $_ = 'abcdefghi';
    /def/; 
    print "$`:$&:$'\n";    # prints abc:def:ghi