0

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.

Jens
  • 67,715
  • 15
  • 98
  • 113
Matt Howes
  • 31
  • 3
  • 1
    Please show your code. – Jens Feb 13 '15 at 18:35
  • 1
    More code needed as an example. Joining the contents of a file into a string is relatively easy, but depends a bit on exactly what you're trying to accomplish. – Sobrique Feb 13 '15 at 19:58

3 Answers3

5

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).

Community
  • 1
  • 1
Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
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; 
}
Sobrique
  • 52,974
  • 7
  • 60
  • 101
1
#!/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;
lnrdo
  • 396
  • 1
  • 13