for i := 1 to n do begin for j := 1 to n do if x[i,j] <> 0 then goto reject; writeln ('The first all-zero row is ', i ); break; reject: end; #### #/usr/bin/env perl use strict; use warnings; use List::MoreUtils qw/all firstidx/; use v5.12; my @array = ( [ qw/ 1 1 1 1 1 / ], [ qw/ 0 1 1 0 0 / ], [ qw/ 0 0 0 0 1 / ], [ qw/ 0 0 0 0 0 / ], [ qw/ 0 1 0 1 0 / ], ); # Test recursive. if( defined( my $row_index = firstrow_recursive( \@array, # Test data 0 # Begin on row 0. ) ) ) { response( $row_index, 'recursive' ); } # Test iterative if( defined( my $row_index = firstrow_iterative( \@array ) ) ) { response( $row_index, 'simple iterative' ); } # Test moreutils if( defined( my $row_index = firstrow_moreutils( \@array ) ) ) { response( $row_index, 'List::MoreUtils' ); } # Test firstrow_function_iterator if( defined( my $row_index = firstrow_functional_iterator( \@array, # Test data \&test_row, # Test function [ 0 ] # Test function params (0 as test pattern) ) ) ) { response( $row_index, 'functional iterator' ); } # -------------------------- Plain iterative version --------- sub firstrow_iterative { my $matrix = shift; ROW: foreach my $row_idx ( 0 .. $#{ $matrix } ) { foreach my $col ( @{ $matrix->[$row_idx] } ) { next ROW if $col != 0; } return $row_idx; } return undef; } # -------------------------- List::MoreUtils version ---------- sub firstrow_moreutils { my $matrix = shift; if( ( my $index = firstidx { all { $_ == 0 } @$_ } @{ $matrix } ) >= 0 ) { return $index; } return undef; } # -------------------------- Recursive version -------------- sub firstrow_recursive { my ( $array, $row_ix ) = @_; my $row = $array->[ $row_ix ]; return undef unless defined $row; if( homogenous_row( $row, 0 ) ) { return $row_ix; } else { return firstrow_recursive( $array, $row_ix +1 ); } } sub homogenous_row { my $row = shift; my $find = shift; foreach my $col ( @{$row} ) { return 0 if $col != $find; } return 1; } # -------------------------- Function functional iterator version -- sub firstrow_functional_iterator { my $matrix = shift; my $test = shift; my $test_params = shift; my $iterator = make_iterator( $matrix ); my $index = 0; while( defined( my $row = $iterator->() ) ) { return $index if $test->( $row, @{ $test_params } ); $index++; } return undef; } sub make_iterator { my $matrix = shift; my $row_idx = 0; return sub { if( not defined( $matrix->[$row_idx] ) ) { $row_idx = 0; return undef; } return $matrix->[$row_idx++]; } } sub test_row { my $row = shift; my $find = shift; foreach my $col ( @{$row} ) { return 0 if $col != $find; } return 1; } # -------------------- Output helper ----------------------- sub response { my( $row, $technique ) = @_; say "First matrix row to contain all zeros is $row,", " using $technique approach."; }