I want 2 inputs in each line in a Perl program.
4 3
3 1
5 7
We can do that in Ruby by this statement
a,b=gets.split.map &:to_i
If this is coming from STDIN
then read it line by line and split
each line by space
while (<STDIN>)
{
my ($first, $second) = split;
# Do what you need with $first and $second
}
This uses defaults of split, with variable $_
(to which input is assigned) and separator pattern ' '
, which stands for any amount of any space and discards leading and trailing spaces. So split;
above is the same as split ' ', $_;
. The newline at the end of each input line is thus dropped.
For more flexibility one can omit the STDIN
filehandle and use
while (<>) { ... }
in which case the files submitted on the command-line are all read line by line, or if no files were given then STDIN
is read.
For reading of input and the diamond operator <>
see I/O Operators in perlop, and for the default input and pattern-searching space variable $_
see General Variables in perlvar.
Checking user input is a whole other matter. To check that these are indeed numbers, a good tool is looks_like_number
from the core module Scalar::Util.
I don't know what else there may be in your program, but I suggest to always start by
use warnings 'all';
use strict;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With