sub getNurls { my( $s, $n ) = @_; my @urls = split /,?(https?:\/\/)/, $s; return map { defined $urls[2*$_-1]?$urls[2*$_-1].$urls[2*$_]:() } (1..$n); } my $max = 2; my $input = q|http://abc.org,http://de,f.org,https://ghi.org|; print "$_\n" for getNurls( $input, $max );