I was wondering how to get multiple inputs from the same input line. For example, the user inputs: 1, 2, 3 . Is there a way to split them and put them into an array.
2 Answers
From perlrequick:
To extract a comma-delimited list of numbers, use
$x = "1.618,2.718, 3.142";
@const = split /,\s*/, $x; # $const[0] = '1.618'
# $const[1] = '2.718'
# $const[2] = '3.142'
The ",\s*" is a regular expression meaning one comma followed by any number of spaces.
Comments
This answer is absolutely right. And if you want to account for the user adding accidental spaces before a comma too (an input like "1, 2 , 3"), you can use
split /\s*,\s*/, $inputstring
So in your case specifically, what you want is
chomp(my $inputstring = <STDIN>);
my ($a, $b, $c) = split( /\s*,\s*/, $inputstring );
chomp removes the trailing newline from the captured input. The parenthesis in split are optional, but make it clear that we are supplying arguments to split. Finally, this code will only look at the first three inputs. If you want to capture all of them more generally, use
chomp(my $inputstring = <STDIN>);
my @inputarray = split( /\s*,\s*/, $inputstring );