I'm trying to process the input of a file character per character, but there are some 1
s showing up of which I don't know where they come from. Consider this example:
File input
First row;
Second row;
Third row;
File test.pl
#!/usr/bin/perl
open FILE, "<input";
my @characters = split //, join //, <FILE>;
for( @characters ) {
print $_;
}
close FILE;
I would expect this script to only print the content of input
(though in a pretty complicated way – it's just an example). However, when I run ./test.pl
, I get this output:
First row;
1Second row;
1
1Third row;
Now my question is: Where do these 1
characters come from?
join //
should be join ''
.
//
, short for $_ =~ m//
, is a match operator. Because it matched successfully, it returned true value 1
.
(split
is special in that it treats split /.../
as something similar to split qr/.../
.)
By the way, always use use strict; use warnings;
. It would have been useful here.
According to the perldoc for join
:
Beware that unlike split, join doesn't take a pattern as its first argument.
See more here: http://perldoc.perl.org/functions/join.html
Changing the first argument to the literal empty string ""
works as you expect:
[ben@lappy ~]$ cat test.pl
#!/usr/bin/perl
open FILE, "<input";
my @characters = split //, join "", <FILE>;
for( @characters ) {
print $_;
}
close FILE;
[ben@lappy ~]$ perl test.pl
First row;
Second row;
Third row;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With