SPUG:Confused field parser seeks...

Michael R. Wolf MichaelRunningWolf at att.net
Sun Jun 1 04:16:42 CDT 2003


Aaron Paul <kalistibot at yahoo.com> writes:

> Thanks that worked great.  Here's my get_newuid:
>
> sub get_newuid{
> my @lines;
> my $lastline;
> my $olduid;
> my ($f1, $f2, $f3, $f4, $f5, $f6, $f7);
> open (PASS,  $draft);
>
> @lines = <PASS>;
> close(PASS);
> $lastline = pop(@lines);
> ($f1,$f2,$f3,$f4,$f5,$f6,$f7)=split /:/, $lastline;
>
> $newuid = ++$f3;
>
> return $newuid;
> }            
>
> --- Brian Hatch <spug at ifokr.org> wrote:
>> 
>> 
>> > my $var="nobody:x:99:99:Nobody:/:/sbin/nologin";
>> > 
>> > $var=~ /(.+):(.+):(.+):(.+):(.+):(.+):(.+)/;
>> 
>> Any reason you don't just want to use
>> 
>> 	($username,$uid,$gid.....) = split /:/, $var;

But be sure to use the third argument to split if you are capturing it
into an array, and there's a possibility of trailing empty fields.

$six  = "one:two:three:four:five:six"
$five = "one:two:three:four:five:"

@six  = split /:/, $six;
@five = split /:/, $five;	# Caution, trailing "empty" field ignored.
@six  = split /:/, $five, -1;   # -1 cures this

The technique presented by previous posters gets around this by
assigning the sixth captured field, or an undef for an uncaptured
field) to the $shell variable.  But watch out if you capture it in an
array and expect that array to have a constant element count.

The way I look at it is simply the difference between data and words.
Use the -1 argument (to signify unlimited) for data, leave it out for
words.

@words = split /\s+/, $line;
@data  = split /:/,   $line, -1;

You want to throw away trailing delimiters when you're looking for
natural language words, but not when you're looking for (possibly
empty) delited data.


-- 
Michael R. Wolf
    All mammals learn by playing!
        MichaelRunningWolf at att.net




More information about the spug-list mailing list