String Concatenation Problem

Could you please see 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

Conclusion:

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

Style error. I need a style below. Is this something wrong in my code? thank.

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

The line read in $linehas a final newlinechar. You must use chompto get rid of it. You have chomp in your code, but it is inappropriate. Move it to the beginning 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 the question in the comment:

To remove leading spaces in a line:

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

To remove a space ending (ending) in a line:

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

To remove the leading and trailing spaces in a string:

$str =~s/^\s+|\s+$//g;
+2

chomp;)

+2

Source: https://habr.com/ru/post/1740647/


All Articles