tags:

views:

74

answers:

2

Hi, Could you please have a look at my code below.

#!C:\Perl\bin\perl.exe 
use strict; 
use warnings; 
use Data::Dumper;  

my $fh = \*DATA;  
my $str1 = "listBox1.Items.Add(\"";
my $str2 = "\")\;";

while(my $line = <$fh>)
{
    $line=~s/^\s+//g;

    print $str1.$line.$str2;

    chomp($line);

}


__DATA__  
Hello
 World

Output:

D:\learning\perl>test.pl
listBox1.Items.Add("Hello
");listBox1.Items.Add("World
");
D:\learning\perl>

Style error. I want the style below. Is ther anything wrong about my code? thanks.

D:\learning\perl>test.pl
listBox1.Items.Add("Hello");
listBox1.Items.Add("World");
D:\learning\perl>
+2  A: 

The line read in $line has a trailing newline char. You need to use chomp to get rid of it. You have chomp in your code, but its misplaced. Move it to the start of the loop as:

while(my $line = <$fh>)
{
    chomp($line);                 # remove the trailing newline.
    $line=~s/^\s+//g;             # remove the leading white space.
    print $str1.$line.$str2."\n"; # append a newline at the end.
}

EDIT:

Answer to the question in the comment:

To remove the leading whitespace in a string:

$str =~s/^\s+//;

To remove the trailing(ending) whitespace in a string:

$str =~s/\s+$//;

To remove the leading and trailing whitespace in a string:

$str =~s/^\s+|\s+$//g;
codaddict
I think the problem is on the regular expression that's selecting the new line character. Take a look at the desired response.
Paulo Santos
@unicornaddictThank you again. Acturally I am developing a C# application, BTW, I want to simplify my C# code with the aid of Perl. :-)
Nano HE
@unicornaddict: How to remove the ending white space? Then I can handle the ending white space like this, ***listBox1.Items.Add("Hello ");*** thank you.
Nano HE
@Nano HE: I've edited my answer.
codaddict
Not quite there with the last one. You'll need `s/^\s+|\s+$//g` to ensure that leading **and** trailing spaces are removed
Zaid
@Zaid: Thanks for pointing :)
codaddict
+2  A: 

Think about the order, between print and chomp ;)

vimma