[Chicago-talk] Doing "-X" tests in a loop

Dan Rench drench+chipm at gmail.com
Tue Oct 6 10:21:27 PDT 2009

On Tue, Oct 6, 2009 at 11:17 AM, Jay Strauss <me at heyjay.com> wrote:

> How would I do "-X" test in a loop?  I've been trying variations on eval,
> but can't get it to work:
>         foreach (qw[-e -r -s]) {
>             eval "$error = $_ unless $_ $xopt{data_file}";
>             print "$_: $error\n";
>         }

Back up a bit. When find yourself using string eval(), stop, because
string eval() is almost never a good idea.

But I'll bite anyway: if you change that "eval" into a "print" you
will see that what's getting eval'ed is something like: " = -e unless
-e somefilename": $error is getting interpolated into a blank string,
where you want it literal, and your first $_ is unquoted. I think you
want $error to contain "-e" or "-r" or "-s", right? Same goes for the
bareword that $xopt{data_file} becomes: you'll need to put quotes
around it. But what kind of quotes? You could pick single quotes, but
you better make sure the name of $xopt{data_file} doesn't contain any
characters that mess up your quoting!

I'll be condemned to Perl Hell (or at least Heck) for this, but I
think this will do what you're asking:

eval qq{\$error = '$_' unless $_ '\Q$xopt{data_file}\E'};

Please don't actually use this code! Get rid of eval(), take the
result of stat($xopt{data_file}) and go from there.

More information about the Chicago-talk mailing list