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.
Myself? Try this:# 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\""; }
$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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |