Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Perl, how can I read pairs of space separated numbers from STDIN?

Tags:

perl

I want 2 inputs in each line in a Perl program.

Input

4 3
3 1
5 7

We can do that in Ruby by this statement

a,b=gets.split.map &:to_i
like image 722
Niket Mishra Avatar asked Mar 10 '23 15:03

Niket Mishra


1 Answers

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;
like image 98
zdim Avatar answered May 08 '23 11:05

zdim