SPUG: reg pattern matching in a loop

Mark Mertel mark.mertel at yahoo.com
Fri Oct 14 17:13:46 PDT 2011


and if the spaces are tabs or other white space characters:

$_ =~ s/\s+/|/g;


On 10/14/2011 4:01 PM, Noah Rømer wrote:
> On 10/14/2011 12:35 PM, Ramon Hildreth wrote:
>
>> open (OUTPUT, ">>$OUTPUTFILE");
>>
>> while (<INPUT>)
>> {
>>          $_ =~ s/ \ +/|/;
>>          print OUTPUT "$PRODUCTLINE $_";
>> }
> Well, there's nothing syntactically wrong with the above. However, it
> may be more limited in effect than you're looking for. The above regex
> will replace the first occurrence of two or more spaces on a line with a
> single '|' character.
>
> In order to replace all contiguous occurrences of the ' ' character with
> a single '|', the regex would be
>
> s/ +/|/g;
>
> No backslash is needed, and the 'g' at the end tells Perl to not stop
> after finding the first matching string on the line. If you don't want
> to condense multiple spaces into a single '|' ('    ' ->  '|'), but want
> a '|' for each space char ('    ' ->  '||||'), then the 'tr' command is
> your friend
>
> tr/ /|/;
>
> This will replace every space found with a pipe character.
>


-- 
Mark Mertel
mark.mertel at yahoo.com



More information about the spug-list mailing list