Perl: the Markov chain saw PerlMonks

### Balance Change

 on Feb 08, 2006 at 16:40 UTC Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

How to write an efficient Perl script to return the balance change of the string?

Balance Change:

Before:

'abc abc abc \textit{abc abc} abc \textit{abc abc \textbf{abc \textbf{
+abc abc} abc} abc} abc.'<br>
[download]

Later:

'abc abc abc <i>abc abc</i> abc <i>abc abc <b>abc <b>abc abc</b> abc</b> abc</i> abc.'

Tanks;

Replies are listed 'Best First'.
Re: Balance Change
by Mago (Parson) on Feb 08, 2006 at 16:47 UTC


perl -e '$_=shift;X while s/\\text(i|b)[tf]\{([^{}]*)\}/<$1>$2<\/$1>/g
+;print;' 'abc abc abc \textit{abc abc} abc \textit{abc abc \textbf{ab
+c \textbf{abc abc} abc} abc} abc.'
[download]

Mago
mago@rio.pm.org

Ok, I understand all of this except for the 'x while.' I understand that x is a repetition operator but I've always seen it written like: '"a" x 80.' However here, there is nothing on the left hand side. Could you explain what it does? I'm guessing it repeats the substitution so that it can find the nested cases but I'd be interested in knowing how it works.

It's not the (lower-case) x operator, it's an (upper-case) unquoted string. Its purpose is to do nothing, but allow there to be a while loop. All the action of the while loop takes place inside its condition.

Caution: Contents may have been coded under pressure.

Thanks for the help everyone, I've also found you can write it like this as well:

while ( <code goes here> ) {}
[download]

The important but being that there's nothing in the {}. This gives us the original one-liner broken up to this:

#!/usr/bin/perl
my $string = 'abc abc abc \textit{abc abc} abc \textit{abc abc \textbf +{abc \textbf{abc abc} abc} abc} abc.'; while ($string =~ s/\\text(i|b)[tf]\{([^{}]*)\}/<$1>$2<\/$1>/g) {} print$string;
[download]

Or you could take out the {} and add a 0, X, or whatever in front of the while (...)

Condition for while, another form would be:

'1 while' or 'A while' or ...

;)

Mago
mago@rio.pm.org

Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://528838]
Approved by ikegami
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (4)
As of 2021-11-28 06:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?

No recent polls found

Notices?