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
chomp
ed (tossing the newline). Next we look for the rightmost slash in the line, usingrindex()
. The next two lines break the string apart usingsubstr()
. If no slash exists, the result of therindex
is-1
, so we hack around that. The final line within the loop prints the results.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. Theforeach
loop prints the results.Here’s one way to do it:
while (<>) { substr($_,0,1) =~ tr/a-z/A-Z/; substr($_,1) =~ tr/A-Z/a-z/; print; }
For each line read by the diamond operator, we use two
tr
operators, each on a different portion of the string. The firsttr
operator uppercases the first character of the line, and the secondtr
operator lowercases the remainder. The result is printed.Another way to do this, using only double-quoted string operators, is:
while (<>) { print "\u\L$_"; }
Give yourself an extra five points if you thought of that method instead.
Get Learning Perl on Win32 Systems now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.