wrote:
> Hello, I have to add to a number in a s/r. My input looks like
>
> Page 1
> Page 2
> Page 3
>
> I want
>
> Page 6
> Page 7
> Page 8
>
> Using /e I'm able to add to a number
> $string=~s/([0-9]+)/$1+1/e
>
> My problem comes from the fact that I don't want to globally replace
> every number. I just want to replace those with "Page #". However, the
> /e option is looking for a method when I add text to the replace
> string.
>
> $string=~s/Page ([0-9]+)/Page $1+1/e; yields
> "Can't call method page without a package or object.
When you use /e, the replacement must be a valid Perl expression. If
you were writing a normal perl expression, and you wanted to assign
your replacement string to a variable, you know this wouldn't work,
right:
$repl = Page $1+1;
Instead, you'd have to do:
$repl = "Page " . ($1+1);
And that's exactly what you have to do in the regexp:
#!/usr/bin/perl
use warnings;
use strict;
while (<DATA>){
s/^Page (\d+)$/"Page " . ($1 + 3)/e;
print;
}
__DATA__
Page 1
Other stuff 5
Page 2
Page 3
Output:
Page 4
Other stuff 5
Page 5
Page 6
> I tried using \Q and \E in my replace string and that doesn't help.
I have no idea what made you think it would. \Q auto-escapes any
regexp-special characters in a double quoted string. What does that
have to do with your current problem?
> I
> even tried using \x.. to output "Page" but that doesn't work either.
I assume you mean the /x modifier, and again I have no idea what makes
you think this would do anything you're looking for.
Throwing code at the program and seeing what sticks is a poor method of
programming.
Paul Lalli