0

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
  • 1
    Absolutely; what have you tried though? Commented Apr 2, 2014 at 17:05
  • I'm thinking something around my($a, $b, $c) = <STDIN>; Commented Apr 2, 2014 at 17:08

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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 );

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.