in reply to Regex frustration

Others have already pointed out some good ideas, but I'd like to expand on BrowserUk's point a bit more. The following is equivalent to his solution, but uses the builtin printf function to accomplish the job. (This way, you also get more control over what your output's going to look like, as a bonus.)
my $rx = qr"^DMSC0022\s+\S+\s+(\w+)$"; my $fmt = "Logfile_Connection_Lost Hostname: %s"; $_="DMSC0022 X10 oswald"; if(my @match = /$rx) { printf "$fmt\n", @match; }
If however you need true positional parameters, like if one of your output strings contains the parameters out of order as in Found $2 at $1, then that won't work for you. You need the following:
my $rx = qr"^DMSC0022\s+\S+\s+(\w+)$"; my $fmt = "Logfile_Connection_Lost Hostname: %1"; $_="DMSC0022 X10 oswald"; if(my @match = /$rx/) { (my $msg = $fmt) =~ s/%\d+/$match[$1]/e; print "$msg\n"; }

Note that you can't easily use literal % characters followed by digits in your output string formats then.

All the solutions in this thread which use qr and whatever else to avoid eval are much cleaner, more efficient, more robust, more secure and more maintainable. If you find yourself using eval "STRING"; you are either doing something very clever or something very stupid. And using it in clever and valid ways is difficult. For a relatively ordinary task, there's always a better device.

Makeshifts last the longest.

Replies are listed 'Best First'.
Re: Re: Regex frustration
by Anonymous Monk on Sep 27, 2002 at 15:19 UTC
    Your suggestion worked great. I agree it is much cleaner. Many thanks for the imparted wisdom!