#!/usr/bin/perl use strict; use warnings; $_ = '2 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2'; while (/(\d) (\d)/g) { my ($first, $second) = ($1, $2); # insert logic for output }