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.

2
  • 1
    Please show your code. Commented Feb 13, 2015 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. Commented Feb 13, 2015 at 19:58

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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; 
}

Comments

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.