-1

As stated here in Call a bash script from a perl script by Igor Chubin, one way to retrieve the result of a bash script from within a perl script is by:

    $result = `/bin/bash /path/to/script`;

Now, my result is actually a series of files, because this script runs a simple find command. The result on the console looks like:

    /path/to/file.extension
    /path/to/file2.extension

I want to take the result, remove white spaces, and concatenate file names seperated with a comma. So that my $result looks like:

    /path/to/file.extension,/path/to/file2.extension

What is the most efficient way to do this? Note that this is taking place within a perl script.

3
  • why do you want to remove white spaces? Commented Dec 11, 2013 at 17:08
  • Using the perl script, the result is fed into a java program as a comma seperated string Commented Dec 11, 2013 at 17:15
  • @mpapec you're right. no need to remove white spaces, replacing the new line with a comma does the job. Commented Dec 11, 2013 at 17:50

3 Answers 3

1
 chomp($result);
 $result =~ tr|\n|,|; # replace every newline with comma
 $result =~ s|\s+||g; # remove whitespaces
Sign up to request clarification or add additional context in comments.

1 Comment

this is working like a charm. Only one problem is that if it returns one file, there is still a comma after it. I want it so that if one file is returned, then DO NOT place comma after it. How would I do that?
1
foreach my $file ( split(/\s+/,$result) ) {
    $file=~s/\s+//g;
    push(@array,$file);
}
print join(",",@array)

Having written this, I would mention that if your script is calling a shell script that does finds, I would recommend looking at File::Find perl module and doing the whole thing in Perl.

Comments

0

You have a string like this:

file_list = "file_1
file_2
file_3
file_4"

And you want to change it to comma separated.

You can use split and join:

 my $comma_separated_list = join ", ", split( /\n/, $nl_separated_file_list );

In two separate commands (which may be easier to see):

my @file_array = split /\n/, $nl_separated_file_list;
my $comma_separated_list = join ", ", $nl_separated_file_list;

The split will produce an array (one for each line. The join will produce a string that is comma separated. The examples here will produce:

$comma_separated_list = "file1, file2, file3, file4, ...";

If you don't want the space, leave it off in the join ", ".

It is possible to do this with a regular expression (replace each instant of a \n with a ,), but I suspect that will take longer to do than a join/split.

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.