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

Community
  • 1
  • 1
AspiringGeek
  • 97
  • 1
  • 11

3 Answers3

1
 chomp($result);
 $result =~ tr|\n|,|; # replace every newline with comma
 $result =~ s|\s+||g; # remove whitespaces
mpapec
  • 50,217
  • 8
  • 67
  • 127
  • 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? – AspiringGeek Dec 11 '13 at 18:58
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.

Mark
  • 71
  • 3
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.

David W.
  • 105,218
  • 39
  • 216
  • 337