This strikes me as a startlingly unusual way to do something standard. I take it you mean to use $exp as a matching expression and then use variable interpolation to get $1 into that string. See, here's the thing. You're working too hard and it's loads easier to make that work correctly. Your original string is interpolating $1 in before the regular expression is even executed. The critical change is to either use non-interpolating single quotes or to escape the $1 as \$1. Your first use of eval is completely superfluous and reduces overall legibility.

# Use a regex object so it's compiled only once $exp = qr|^DMSC0022\s+\S+\s+(\w+)$|; # Use a non-interpolating string (or escape the $1 as \$1 $str = 'Logfile_Connection_Lost Hostname: $1'; # I can only assume you are assigning to $_ # because this is a snippet from some larger code. On it's # own this is really weird. Normal code would do something # like "DMS ..." =~ $exp instead. $_ = "DMSC0022 X10 oswald"; # Force $exp to execute (don't just eval it, this is more correct) if ( $_ =~ $exp ) { # the eval() is still needed to force the source code # to generate. This is still silly. eval "print \"$str\""; }
Myself? Try this:
$exp = qr/\w+$/; $str = "Logfile_Connection_Lost Hostname:"; $input = "DMSC0022 X10 oswald"; ($hostname) = $input =~ m/$exp/g; print "$str$hostname" if defined $hostname;

That's more legible and will run faster as well.

Update: I completely rewrote the node since it sucked initially.


In reply to Re: Regex frustration by diotalevi
in thread Regex frustration by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.