#!/usr/bin/perl -w use warnings; use strict; my ($tag, %list); while (){ next unless /./; if (/^(\w+)/){ $tag = $1; next; } if (/^-- (\w+)/){ push @{$list{$tag}}, $1; } } for my $type (@{$list{main}}){ if ($list{$type}){ for (@{$list{$type}}){ print "main $type $_\n"; } } else { print "main $type\n"; } } __END__ main -- check -- check1 check -- computing -- net check1 -- computing2 -- net2 computing -- community The output should be main check computing community main check net main check1 computing2 main check1 net2 But the output is coming as below: main check computing1 main check net main check1 computing2 main check1 net2