
japhy
Enthusiast
/ Moderator
May 27, 2000, 6:36 PM
Post #2 of 3
(6591 views)
|
First, do you know WHY all the lines but the first have an extra space in the front? Because when you do <BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR> $string = "@array"; </pre><HR></BLOCKQUOTE> what you're actually saying is <BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR> $string = join $", @array; </pre><HR></BLOCKQUOTE> $" is a special Perl variable that holds the list separator -- the string that Perl puts in between elements of an array when the array is inside double quotes. It defaults to a single space: " ". Therefore, all the elements (except the first) of @array have a " " put in front of them when they are put in $string. Now you know WHY that happens. Now you want to know how to FIX it. Here are several ways. <BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR> # 1. use while() while (<FILE> ) { print OUTPUT; } # 2. use join() $string = join "", <FILE>; print OUTPUT $string; # 3. use the proper regex @lines = <FILE>; $string = "@lines"; $string =~ s/^ //mg; </pre><HR></BLOCKQUOTE> I strongly discourage using method 3, because it requires you store the lines of the file in an array, and then store them in a string, and then uses a regex on the string -- these are unnecessary. I suggest method 1 be used whenever possible. About the regex... you need to use <BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR> s/^ //gm </pre><HR></BLOCKQUOTE> First, the /m modifier changes the meanings of ^ and $. Ordinarily, ^ matches at the FRONT OF A STRING, and $ matches at the END OF A STRING (or before the ending newline of a string). With /m on, ^ matches at the front of a string as well as IMMEDIATELY after any newline, and $ matches at the end of a string as well as IMMEDIATELY before any newline. The "^ " then means "match a single space at the BEGINNING of the string, or IMMEDIATELY after a \n". And we have the /g modifier because we want to do this globally, for the entire string. However, this regex needs to be changed OH-SO-SLIGHTLY, to be perfect. What if the first element of your array REALLY DOES have a space as its first character? You don't want to delete it. You only want to remove the first character of every line BUT THE FIRST. So that means remove a space after a newline. <BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR> @lines = <FILE>; $string = "@lines"; $string =~ s/(?<=\n) //g; </pre><HR></BLOCKQUOTE> This doesn't need ^ or /m. This just says "remove a space that is preceeded by a newline, and do this globally." [This message has been edited by japhy (edited 05-27-2000).]
|