Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Strings

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
Hi
I have a little problem with a string.
I have a text file with names like this:


benny
fredrik
bodil
harry
bill
susan
jenny

I now how to use $lines =~ s /bill/billy_boy/g;
bill will be billy_boy

But how do I do when a want to replace all names expect bill to
become billy_boy

When finished it should look like this

billy_boy
billy_boy
billy_boy
billy_boy
bill
billy_boy
billy_boy



/Thanks
 
i'm sure there's an easier way to do this, but...


@file = <FILE>;

foreach(@file)
{
if($_ =~ /bill/g)
{

}
else
{
s/.+/billy_boy/g;
}
} adam@aauser.com
 
One step easier yes....
i'm sure there's an easier way to do this, but...

This will work fine, the !~ or not match .. is what you are looking for...

Jams

@file = <FILE>;
$i = 0;
while (@file$i)
{
if(@file[$i] !~ /bill/gi)
{
@file[$i] = &quot;billy_boy&quot;;
}
}
Falazar@yahoo.com
 
i think you're taking out the newlines with that code. adam@aauser.com
 
You can always solve one problem lots of different ways in Perl - here's another solution - slight variation on the if:

my @a = (&quot;abc&quot;, &quot;bill&quot;, &quot;xyz&quot;);
my @b = @a;
foreach (@b) {
s/.+/billy_boy/ if ($_ !~ /bill/);
}
print &quot;Before: array = &quot; . join(&quot;, &quot;, @a) . &quot;\n&quot;;
print &quot;After: array = &quot; . join(&quot;, &quot;, @b) . &quot;\n&quot;;

Here's the output:
-------------
Before: array = abc, bill, xyz
After: array = billy_boy, bill, billy_boy

I actually prefer not to use this method of specifying the &quot;if&quot; after the &quot;then&quot; part, but it is available and it does work, so I thought I'd present it. It does make for shorter code.
Hardy Merrill
Mission Critical Linux, Inc.
 
I see what you want, you want to say:

[tt]s/^(not bill)$/billy_boy/[/tt]

I'm pretty sure this is what negative lookaheads are for:
[tt]
@arr = qw(abc bill xyz);
foreach (@arr) {
s/^(?!bill).*$/billy_boy/;
}
print @arr;
[/tt]
This works perfect in my script. (?!...) means that it will match the current position only if the next thing the regex engine finds does not match '...'
Hope this is what you want.
&quot;If you think you're too small to make a difference, try spending a night in a closed tent with a mosquito.&quot;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top