(W newline) A file operation was attempted on a filename, and that
operation failed, PROBABLY because the filename contained a newline,
-PROBABLY because you forgot to chop() or chomp() it off. See
-L<perlfunc/chomp>.
+PROBABLY because you forgot to chomp() it off. See L<perlfunc/chomp>.
=item Unsupported directory function "%s" called
Example:
while (<>) {
- chop;
+ chomp;
next unless -f $_; # ignore specials
#...
}
=item chop
Chops off the last character of a string and returns the character
-chopped. It's used primarily to remove the newline from the end of an
-input record, but is much more efficient than C<s/\n//> because it neither
+chopped. It is much more efficient than C<s/.$//s> because it neither
scans nor copies the string. If VARIABLE is omitted, chops C<$_>.
-Example:
-
- while (<>) {
- chop; # avoid \n on last field
- @array = split(/:/);
- #...
- }
-
If VARIABLE is a hash, it chops the hash's values, but not its keys.
-You can actually chop anything that's an lvalue, including an assignment:
-
- chop($cwd = `pwd`);
- chop($answer = <STDIN>);
+You can actually chop anything that's an lvalue, including an assignment.
If you chop a list, each element is chopped. Only the value of the
last C<chop> is returned.
open(PASSWD, '/etc/passwd');
while (<PASSWD>) {
- ($login, $passwd, $uid, $gid,
+ chomp;
+ ($login, $passwd, $uid, $gid,
$gcos, $home, $shell) = split(/:/);
#...
}
-(Note that $shell above will still have a newline on it. See L</chop>,
-L</chomp>, and L</join>.)
=item sprintf FORMAT, LIST
Unix does the same thing on ttys in canonical mode. C<\015\012>
is commonly referred to as CRLF.
+A common cause of unportable programs is the misuse of chop() to trim
+newlines:
+
+ # XXX UNPORTABLE!
+ while(<FILE>) {
+ chop;
+ @array = split(/:/);
+ #...
+ }
+
+You can get away with this on Unix and MacOS (they have a single
+character end-of-line), but the same program will break under DOSish
+perls because you're only chop()ing half the end-of-line. Instead,
+chomp() should be used to trim newlines. The Dunce::Files module can
+help audit your code for misuses of chop().
+
+When dealing with binary files (or text files in binary mode) be sure
+to explicitly set $/ to the appropriate value for your file format
+before using chomp().
+
Because of the "text" mode translation, DOSish perls have limitations
in using C<seek> and C<tell> on a file accessed in "text" mode.
Stick to C<seek>-ing to locations you got from C<tell> (and no