develooper Front page | perl.perl5.porters | Postings from September 2022

Not so special case for split function

Thread Next
From:
Ivan Vorontsov
Date:
September 16, 2022 08:08
Subject:
Not so special case for split function
Message ID:
20220916110823.ac2582772c0ddcc98b56e420@yandex.ru
split function can take a string composed of a single space character as
a pattern to emulate the default behavior of the awk. re pragma allows
to specify flags for every regular expression. Two things combined break
my expectation.

$ perl -e 'my @foo = split(" ", "a b c"); print("<$_>") for @foo; print("\n")'
<a><b><c>
$ perl -MO=Deparse -e 'my @foo = split(" ", "a b c"); print("<$_>") for @foo; print("\n")'
my @foo = split(' ', 'a b c', 0);
print "<$_>" foreach (@foo);
print "\n";

$ perl -Mre=/x -e 'my @foo = split(" ", "a b c"); print("<$_>") for @foo; print("\n")'
<a>< ><b>< ><c>
$ perl -Mre=/x -MO=Deparse -e 'my @foo = split(" ", "a b c"); print("<$_>") for @foo; print("\n")'
BEGIN {
    $^H{'reflags'} = '8';
}
my @foo = split(/ /x, 'a b c', 0);
print "<$_>" foreach (@foo);
print "\n";

In the first case split gets a string as a pattern, in the second it is
match operator with x flag, which effectivly makes it to be an empty
pattern hence the result of the splitting.

autosplit command line option also ends up broken.

$ cat ./foo.txt
a b c

$ perl -ae 'print("<$_>") for @F; print("\n")' ./foo.txt
<a><b><c>
$ perl -MO=Deparse -ae 'print("<$_>") for @F; print("\n")' ./foo.txt
LINE: while (defined($_ = readline ARGV)) {
    our @F = split(' ', $_, 0);
    print "<$_>" foreach (@F);
    print "\n";
}

$ perl -Mre=/x -ae 'print("<$_>") for @F; print("\n")' ./foo.txt
<a>< ><b>< ><c>
$ perl -Mre=/x -MO=Deparse -ae 'print("<$_>") for @F; print("\n")' ./foo.txt
BEGIN {
    $^H{'reflags'} = '8';
}
LINE: while (defined($_ = readline ARGV)) {
    our @F = split(/ /x, $_, 0);
    print "<$_>" foreach (@F);
    print "\n";
}

I guess I get what ask for by using re pragma. But my expectation is
to treat a string with a space more as a flag for the awk-like behavior
than an actual pattern.

-- 
Ivan Vorontsov <ivrntsv@yandex.ru>

Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About