I have a string, say: “5 3*3 4*1 6*3 14*4 3*2 2*3 4”
I want this string to become an array with elements:
@array = ( “5”, “3” x 3, “1” x 4, “3” x 6, “4” x 14, “2” x 3, “3” x 2, “4” );
I’m guessing there’s a better (shorter) way than this:
$string = "5 3*3 4*1 6*3 14*4 3*2 2*3 4";
@array = split (/\s+/,$string);
foreach(@array) {
if ( /\*/ ) {
s/^(\d+)\*(\d+)/"$2" x $1/g;
} else {
print "$_\n";
$_ = '"'. $_ .'"';
}
}
EDIT: This code actually does what I say it should do above in the original question. But it’s not actually what I want. I want the final array to look like:
@array = (5, 3, 3, 3, …)
Algorithm:
Implementation (oneliner)
Implementation (normal)
Do note that the repetition operator used on strings repeats and concatenates the strings:
But used on a list, it returns a list with repeated elements: