Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: How do I replace certain character if condition exists

by BrowserUk (Patriarch)
on Apr 17, 2003 at 15:02 UTC ( [id://251224]=note: print w/replies, xml ) Need Help??


in reply to How do I replace certain character if condition exists

This code will correct the gross imbalance of parens without requiring to delete them all. As is, it works line by line, but would operate on a whole file if you slurped it.

#! perl -slw use strict; while(<DATA>) { my $count=0; chomp; print; $count += $1 eq '(' ? +1 : -1 while m[([()])]g ; s[(^.*?)\(] [$1] while $count-- > 0; s[(.*)\)(.*?$)][$1$2] while ++$count < 0; print; } __DATA__ test (test) test (test (test (test)) (test (test) (() (()) (((())))) ( () (()) ( ( () ) ) )) (( () (()) ( ( () ) ) ) ((( test test ))) (((test) (test)))

All it does is count the number of opens and closes and delete enough of whichever is in excess from the beginning or end to correct any imbalance.

In most cases, that probably means that the resultant parenthesizing would not reflect the original intent, but it is difficult to see how to determine what that intent was without specific knowledge.


Examine what is said, not who speaks.
1) When a distinguished but elderly scientist states that something is possible, he is almost certainly right. When he states that something is impossible, he is very probably wrong.
2) The only way of discovering the limits of the possible is to venture a little way past them into the impossible
3) Any sufficiently advanced technology is indistinguishable from magic.
Arthur C. Clarke.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://251224]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (5)
As of 2024-04-19 06:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found