Ingo Bürk
Ingo Bürk

Reputation: 20043

Mysterious '1' when processing string character-wise

I'm trying to process the input of a file character per character, but there are some 1s 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?

Upvotes: 4

Views: 114

Answers (2)

Ben
Ben

Reputation: 1210

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;

Upvotes: 7

user2525443
user2525443

Reputation: 278

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.

Upvotes: 14

Related Questions