use Modern::Perl; my ( @table, $id1, $id2, $i ); push @table, [ (split) ] while ; do { $id1 .= $_->[2]; $id2 .= $_->[3] } for @table; $id1 =~ s/(?<=(.))(0+)(?=(.))/$1==$3?$1 x length $2:$2/eg; $id2 =~ s/(?<=(.))(0+)(?=(.))/$1==$3?$1 x length $2:$2/eg; $i = 0; say "$_->[0]\t$_->[1]\t" . substr( $id1, $i, 1 ) . "\t" . substr( $id2, $i++, 1 ) for @table; __DATA__ 1 100 1 2 101 200 1 2 201 300 1 0 301 400 1 0 401 500 0 2 501 600 0 2 601 700 0 0 701 800 1 1 801 900 1 2