1

This is the code:

my $t = "abc\nfoo\nbar";
my @a = split(/\n/g, $t);
print $#a . " lines\n";
foreach my $x (@a) {
    print 'line: ' . $x . "\n";
}

It prints:

2 lines
line: abc
line: foo
line: bar

Why 2 lines while there are three lines? :)

yegor256
  • 102,010
  • 123
  • 446
  • 597
  • 1
    You're getting the index of the last element, but there are other methods to get what you want. See the duplicate question. – tadman Nov 09 '22 at 04:12
  • @tadman What's wrong with my method of getting array size? – yegor256 Nov 09 '22 at 04:15
  • 4
    "_What's wrong with my method of getting array size?_" -- your method gives you the index of the last element, which is one less than the array size since in Perl array index stars from zero. So yes you could say `my $size = $#a + 1;` -- or, you can use `@a` in scalar context, which gives array size so `my $size = @a;` – zdim Nov 09 '22 at 04:35
  • 1
    Re "*What's wrong with my method of getting array size?*", It doesn't work. You already discovered that. Now, if you want the last index of an array, then `$#a` is what you want. – ikegami Nov 09 '22 at 04:42
  • 1
    Tip: Don't use the `g` flag on split patterns. The pattern is supposed to match what separates your list items, so the `g` makes no sense. Thankfully, this error is being ignored. But it would be nice to fix it. – ikegami Nov 09 '22 at 14:07

0 Answers0