my $line = "file1.gz file2.gz file3.gz";
my @abc = split('', $line);
print "@abc\n";
Expected output:
file1.gz
file2.gz
file3.gz
I want the output to be file1.gz
in $abc[0]
, file2.gz
in $abc[1]
, and file3.gz
in $abc[2]
. How do I split $line
?
You already have multiple answers to your question, but I would like to add another minor one here that might help to add something.
To view data structures in Perl you can use
Data::Dumper
. To print a string you can usesay
, which adds a newline character"\n"
after every call instead of adding it explicitly.I usually use
\s
which matches a whitespace character. If you add+
it matches one or more whitespace characters. You can read more about it hereperlre
.I found this one to be very simple!
output:
Here take a look at this tutorial to find more on Perl regular expression and scroll down to More matching section.
Just use /\s+/ against '' as a splitter. In this case all "extra" blanks were removed. Usually this particular behaviour is required. So, in you case it will be:
Having
$line
as it is now, you can simply split the string based on at least one whitespace separatorthen
or
I prefer using
()
forsplit
,print
andfor
.Splitting a string by whitespace is very simple:
This is a special form of
split
actually (as this function usually takes patterns instead of strings):Here's an answer for the original question (with a simple string without any whitespace):
Perhaps you want to split on
.gz
extension:Here I used
(?<=...)
construct, which is look-behind assertion, basically making split at each point in the line preceded by.gz
substring.If you work with the fixed set of extensions, you can extend the pattern to include them all: