writes:
>
> use strict;
> use warnings;
>
> open(IN, 'myfile.txt') or die "Open failed..$!\n";
> while(my @arr = split /:/, <IN>)
> {
> #print "* $_ *\n";
> if (/^#/) { print "Comment found\n"; }
> }
> close(IN);
>
> I attempted to read the filename (line-by-line), split it using ':' as
> seperator and stored the contents in an array. My IF check fails
> despite the file having only perl comments.
> $cat myfile.txt
> #Simple comment
> #another comment
> ##end
>
> I think that $_ is being set to undef by split.
> The split documentation does not say that $_ is modified by split.
>
> Can someone please explain why $_ is being modified here.
$_ is not being modified by 'split'; it's in fact never set at all.
You 'while' statement does not both iterate over the lines in the file
and over the items in the split list; it only does the former. You need
another iteration level in your code:
while(my @arr = split /:/, <IN>) {
for (@arr) {
#print "* $_ *\n";
if (/^#/) { print "Comment found\n"; }
}
}
(There may be more to say about this code - I'm new myself - but this
works.)
It's the file you want to read, by the way, not the filename.
I see that I'm assuming that your code was nearly correct already, but
do you want '#' to start a comment within each ':'-delimited field, or
only at the beginning of a line? The latter is more usual. If only at
the beginning of a line, it doesn't make sense to check for that while
iterating over the result of 'split'. I leave the necessary changes as
an exercise.