O'Reilly logo

Learning Perl, Second Edition by Randal L. Schwartz, Tom Christiansen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

A.14. Chapter 15

  1. Here's one way to do it:

    while (<>) {
        chomp;
        $slash = rindex($_,"/");
        if ($slash > -1) {
            $head = substr($_,0,$slash);
            $tail = substr($_,$slash+1);
        } else {
            ($head,$tail) = ("", $_);
        }
        print "head = '$head', tail = '$tail'\n";
    }

    Each line read by the diamond operator is first chomped (tossing the newline). Next we look for the rightmost slash in the line, using rindex(). The next two lines break the string apart using substr(). If there's no slash, the result of the rindex is -1, so we hack around that. The final line within the loop prints the results.

  2. Here's one way to do it:

    chomp(@nums = <STDIN>); # note special use of chomp
    @nums = sort { $a <=> $b } @nums;
    foreach (@nums) {
        printf "%30g\n", $_;
    }

    The first line grabs all of the numbers into the @nums array. The second line sorts the array numerically, using an inline definition for a sorting order. The foreach loop prints the results.

  3. Here's one way to do it:

    open(PW,"/etc/passwd") || die "How did you get logged in?";
    while (<PW>) {
        chomp;
        ($user, $gcos) = (split /:/)[0,4];
        ($real) = split(/,/, $gcos);
        $real{$user} = $real;
        ($last) = (split /\s+/, $real)[-1];
        $last{$user} = "\L$last";
    }
    close(PW);
    
    for (sort by_last keys %last) {
        printf "%30s %8s\n", $real{$_}, $_;
    }
    
    sub by_last { ($last{$a} cmp $last{$b}) || ($a cmp $b) }

    The first loop creates %last hash, consisting of login names for keys and user's last names for the corresponding values, and the %real hash, containing the full real names instead. The last ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required