qr| $owner # proc owner \s+ # one or more whitespace (\d+) # capture one or more digits .* # everything up until... \s+ # the last whitespace $processName # proc name $ # end of string |x #### use warnings; use strict; use feature 'say'; getPids('top', 'ubuntu'); sub getPids{ my ($processName,$owner) = @_; my $ps; my $pid; my $command = "/bin/ps auwwwx | grep $processName | grep -v grep | grep -v 'sh -c' "; $ps = `$command`; # print $ps; my @lines = split( "\n",$ps); # print @lines; foreach my $line (@lines){ if ($line =~ qr|$owner\s+(\d+).*\s+$processName$|){ say "Found $processName in getPids() owned by $owner. PID is $1"; }else{ say "Loser"; } } } #### Found top in getPids() owned by ubuntu. PID is 9377 # orig: ubuntu 9377 0.0 0.1 23668 1600 pts/2 S+ 18:23 0:00 top