[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: [OT] Perl: exec and $variables



On Sat, Jul 21, 2001 at 02:31:58PM +0200, Sven Burgener wrote:
> On Sat, Jul 21, 2001 at 01:46:25PM +0200, Joost Kooij wrote:
> > On Sat, Jul 21, 2001 at 01:04:40PM +0200, Sven Burgener wrote:
> > > my $BEGINREGEX   = "sprintf(\"^<!-- // begin of news\$no // !-->\$\")";
> > 
> > Please tell us what you're trying to accomplish first.  It is unclear
> > what assumptions you are making.
> 
> What I want is the variable $BEGINREGEX to contain a string like so:
> 
> ^<!-- // begin of news1 // !-->$
> 
> or
> 
> ^<!-- // begin of news2 // !-->$
> 
> The digit after the "news" should be whatever $no is set to at that
> point in the script.
 
You are still not telling really what you want to accomplish, but I infer
that you want to match lines like:

  <!-- // begin of news1 // !-->

To test if the entire $line matches it, you would write:

  $line =~ m(^<!-- // begin of news1 // !-->$);

Notice that I used the "m" operator explicitly, so I can use an alternate
regexp delimiter, or else I would have had to escape each of the slashes
in your pattern.

What is the need for the seperate variable $BEGINREGEX?  It complicates
things enormously when you want a variable $no to be evaluated whenever
$BEGINREGEX is evaluated.  The only sane way out is to completely reevaluate
$BEGINREGEX after each change to $no.  To do that successfully, you have
to escape '$', '"', and '\' and then escape some of the escapes, but others
not, depending on wheter they should never be expanded, expanded in the 
eval or expanded when applying the regexp.  I wouldn't touch that with a 
ten foot pole if I were you.  If you succeed at it, you have great job
security, and a maintenance nightmare.

Easier is to not use a $BEGINREGEX at all:

  $line =~ m(^<!-- // begin of news$no // !-->$);

should always work, for the current value of $no.

> > > my $no = 1;
> > > my $bla = eval($BEGINREGEX);
> > > print "$bla\n";
> > > 
> > > $bla is empty for some reason.
> > 
> > You probably do not want to use eval here, or at least not in this way.
> 
> What should I do then?
> 
> It's simple, really. I am sure I am just making a stupid mistake.
> 
> my $BEGINREGEX = "sprintf(\"^<!-- // begin of news\$no // !-->\$\")";
> my $no = 99;
> my $bla = eval($BEGINREGEX);
> print "regex string: $bla\n";
> 
> What should be printed:
> 
> regex string: ^<!-- // begin of news99 // !-->$

Why are you putting the sprintf in the regexp at all?  The '^' and '$' anchors
only work when at the begin, resp. at the end of the whole regexp.  I think 
that the use of sprintf is unnecessary, and even complicates things enormously.
 
> But it isn't, so what am I doing wrong here?

AFAICS, you're just not doing it in the most straightforward way.
Try to use fixed regexps, and leave the $no in it, so it will be expanded
every time perl uses the regexp.

Cheers,


Joost



Reply to: