ronix has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks,

New guy here again. I am trying to list the available UIDs between 200 and 250 on an AIX system. I have a working solution but it's ugly. I am sure there are some of you with Perl PHDs that can suggest a more elegant solution then the one below :) Please let me know what you suggest, thanks!

#!/usr/bin/perl -W my $alluids = "/tmp/uid_list.file"; open (UIDS, ">$alluids") || die "Cannot open file $alluids\n"; while (my @uidlst = getpwent) { print UIDS "$uidlst[2]\n"; } close(UIDS); open (UIDS, "<$alluids") || die "Cannot open file $alluids\n"; while(<UIDS>) { chomp; push(@arr, $_); } close(UIDS); my %hash = map { $_ => 1 } @arr; foreach $i (200..250) { if ( ! defined $hash{$i} ) { print "$i "; } }

Replies are listed 'Best First'.
Re: Finding the lowest available UIDs
by Limbic~Region (Chancellor) on Nov 11, 2008 at 21:02 UTC
    ronix,
    You could use the solution I provided in your last post to put all the entries in an array. Then sort the array in ascending order by the UID and you can slice and dice it any which way you want. Since you are now asking a more specific question then your previous post and what you mentioned in the CB, try this instead
    #!/usr/bin/perl use strict; use warnings; my %used; while (my @entry = getpwent) { my $uid = $entry[2]; next if $uid < 200 || $uid > 250; $used{$uid} = 1; } for (200 .. 250) { next if $used{$_}; print "$_ is free\n"; }
    s/warning/warnings/ thanks to Your Mother in /msg

    Cheers - L~R

Re: Finding the lowest available UIDs
by JavaFan (Canon) on Nov 11, 2008 at 20:57 UTC
    Something like:
    my @uids; while (my @list = getpwent) { $uids[$list[2]]++; } print $_ for grep {!$uids[$_]} 200 .. 250;

      On OS X this gives-

      Out of memory during array extend at - line 3.
        If your UIDs get too high, either add a test in the loop (no need to do anything if the UID is above 250), or use a hash instead of an array.
Re: Finding the lowest available UIDs
by ronix (Novice) on Nov 11, 2008 at 21:13 UTC
    wow very cool guys!!

    Thanks for the fast response. Both solutions work beautifully, sorry the for the previous confusion.