Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Having Trouble Removing a Newline from a Multiline String

by Dru (Hermit)
on Oct 02, 2008 at 06:27 UTC ( [id://714958]=perlquestion: print w/replies, xml ) Need Help??

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

Greetings Monks,

I am in need of your enlightment. I have a multiline string and sometimes it includes a blank newline, which I need to remove. I figured this was easy enough and thought this little subsitution regex would accomplish this: $vulns =~ s/^$//m; but no luck. I know my regex is matching, because if I use: $vulns =~ s/^$/-/m; it replaces that line with a dash.

Here is a sample string that I am trying to match:
5 Active Microsoft SQL Server 2000 Service Pack 4 Missing 5 Active Microsoft SQL Server Multiple Vulnerabilities 4 Active port 1433/tcp Microsoft SQL Server 2000 Latest Patch Not 4 Active port 3067/tcp Microsoft SQL Server 2000 Latest Patch Not 4 Active port 1723/tcp PPTP VPN Configuration Allows Weak MS-CHAPv1
Thanks,
Dru

Perl, the Leatherman of Programming languages. - qazwart

Replies are listed 'Best First'.
Re: Having Trouble Removing a Newline from a Multiline String
by ikegami (Patriarch) on Oct 02, 2008 at 06:57 UTC

    $ matches the point between \n and the character before it.

    print "a\n\nc\n" =~ / a\n ^ $ c\n /mx ?1:0, "\n"; # 0 print "a\n\nc\n" =~ / a\n ^ $ \n c\n /mx ?1:0, "\n"; # 1

    Since $ matches before the newline, it doesn't ever actually match the newline, and thus the newline is not getting substituted. What you want to do is remove newlines that start lines.

    $_ = "abc\n" . "def\n" . "\n" . "jkl\n" . "\n" . "\n" . "stu\n"; s/^\n//mg; print;
    abc def jkl stu
      That did the trick, thank you.

      Thanks,
      Dru

      Perl, the Leatherman of Programming languages. - qazwart
Re: Having Trouble Removing a Newline from a Multiline String
by BrowserUk (Patriarch) on Oct 02, 2008 at 06:39 UTC
Re: Having Trouble Removing a Newline from a Multiline String
by jwkrahn (Abbot) on Oct 02, 2008 at 11:01 UTC

    Another way to do what you want:

    $vulns =~ tr/\n//s;

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (8)
As of 2024-04-18 16:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found