Dave's Brain

Browse - Programming Tips - How do I break up a string into lines in perl?

Date: 2012may18
Language: perl

Q.  How do I break up a string into lines in perl?

A.  Here you go:

foreach $line (split(/\r\n|\n/, $contents)) { print "$line\n"; }
This handles lines that end in CR-LF (line HTTP and Windows) or LF (like Linux and iOS); the vast majority of situations. It also preserves blank lines. If you want to read a file into lines don't to the above, to do this:
open(FILE, 'myfile.txt'); while ($line = <FILE>) { chop($line); print "$line\n"; } close(FILE);

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.