my @chains = qw(INPUT OUTPUT FORWARD); my @rules = open_file($rules); foreach (@chains) { for my $rule (@rules) { print $rule if ( $_ eq $rule ); } } #### my FILE>> INPUT -p tcp -s 10.0.12.1 -j ACCEPT FORWARD -p udp -d 10.0.12.4 -j ACCEPT OUTPUT -p tcp -s 10.0..12.5 -j ACCEPT FILE my @chains = qw(INPUT OUTPUT FORWARD); I Loop the array open then file and try to match first array item push on to new array until then next array item match.