问题
I need to concatenate an undefined number of strings with Perl to create one larger string.
$concatenated_string = $string1 . $string2 . $string3 #..and so on for all strings provided in the file which was opened earlier in the program.
I am just a beginner, but I could not find any question on here relating to it. Any help is much appreciated.
回答1:
As I have mentioned elsewhere:
When you find yourself adding an integer suffix to variable names, think "I should have used an array".
Then you can use join('', @strings).
回答2:
I'm guessing a bit, because you don't have much example code.
But have you considered something like this:
open ( my $input_fh, "<", "filename" ) or die $!;
my $concatenated_string;
while ( my $line = <$input_fh> ) {
chomp ( $line ); #if you want to remove the linefeeds.
$concatenated_string .= $line;
}
回答3:
#!/usr/bin/env perl
# Modern Perl is a book every one should read
use Modern::Perl '2013';
# Declaring array to store input
my @info;
# Using a loop control to store unknow number of entries
while (<STDIN>) { # Reading an undefined number of strings from STDIN
# Removing the \n
chomp;
# Stacking input value into array
push(@info, $_);
}
# printing all entries separated by ","
say join(', ', @info);
# exit program indicating success (no problem)
exit 0;
OR
my $stream;
$stream .= $_ while <STDIN>;
print $stream;
来源:https://stackoverflow.com/questions/28506301/perl-concatenating-a-undefined-number-of-strings-into-one-string