Mysterious "1" in character string processing

I am trying to process the input of a file character per character, but there are some 1 of which I do not know where they come from. Consider this example:

input file

 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 print only the input content (although in a rather 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 characters come from 1 ?

+4
source share
2 answers

join // must be join '' .

// , the abbreviation of $_ =~ m// , is a conjugation operator. Since it successfully matched, it returned the true value of 1 .

(The split feature is that it treats split /.../ as something similar to split qr/.../ .)

By the way, always use use strict; use warnings; use strict; use warnings; . That would be helpful here.

+14
source

According to perldoc for join :

Beware that unlike split, join doesn't take a pattern as its first argument.

More details here: http://perldoc.perl.org/functions/join.html

Changing the first argument to the literal empty string "" works as you would 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; 
+7
source

Source: https://habr.com/ru/post/1488564/


All Articles