#!/usr/bin/perl use strict; use warnings; my(@hosts, @ports); while () { push @hosts, $1 while /HOST=(\S*?)\./g; # nongreedy quantifier *? push @ports, $1 while /PORT=(\S*)/g; } print "Hosts: ", join(", ", sort @hosts), "\n"; print "Ports: ", join(", ", sort @ports), "\n"; __DATA__ HOST=machine1-basement.xyz.com PORT=1234 HOST=machine2-attic.xyz.com PORT=9999 HOST=machine3-garage.xyz.com PORT=5555