SPUG:Split question

Michael R. Wolf MichaelRunningWolf at att.net
Sat Mar 22 16:18:28 CST 2003


"Michael R. Wolf" <MichaelRunningWolf at att.net> writes:

[...]

>     # root:q.mJzTnu8icF.:0:10:superuser:/:/bin/csh
>     # xxx::100:100:mb_daemon:/usr/make-believe/daemon:
>     my $line = qx(head /etc/passwd);
>     my ($id, @other_fields, $shell) = split /,/, $line, -1;

                                               ^
Should be a colon, not a comma ---------------/

Thanks, David for noticing.

And also, as David pointed out, the array is greedy.  I knew that, but
hadn't paid attention as I sketched an illustration.  It was my
attempt to document the field mnemonically.  Perhaps this is a better
illustration:

(undef, undef, undef, undef, undef, undef, $shell) = 
    split /,/, $line, -1;

With a 3rd argument of -1, $shell will get an empty string because the
split will always return a 7 element list.

Without the 3rd argument, the split will ignore trailing delimiters,
thereby returning a list of different length on different lines.   In
that case, $shell gets undef, and you get (you are using -w, aren't
you) errors later in your code regarding an undef value.

Said differently, supplying the 3rd argument makes split behave more
consistently with the data, for this kind of data.

Thanks again for picking up the nits.

Michael

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




More information about the spug-list mailing list