Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysterious '1' when processing string character-wise

Tags:

perl

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?

like image 509
Ingo Bürk Avatar asked Nov 30 '22 12:11

Ingo Bürk


2 Answers

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.

like image 130
user2525443 Avatar answered Dec 06 '22 07:12

user2525443


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;
like image 33
Ben Avatar answered Dec 06 '22 07:12

Ben