The reason the regex doesn't work is because of this portion: (\d*)\w+\s+. What that does is search for zero or more digits and puts them in a capture group (\d*), as long as the next character is a word char (\w+), followed by at least one whitespace (\s+).

A digit is a word character. Since the only thing immediately after the proc ID is whitespace, the \w+ steals the last digit from it, before the next whitespace \s+. It only takes the last one, because \d* is greedy, and will gulp everything as far as it can until the regex doesn't match, then it backtracks.

The regex can be simplified a bit: qr|$owner\s+(\d+).*\s+$processName$|. Explained:

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

In action:

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"; } } }

Output:

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

In reply to Re: Regex and PID issue by stevieb
in thread Regex and PID issue by JonesyJones

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.