in reply to Re^3: Loop through array or filehandle
in thread Loop through array or filehandle

Thanks again. I think you have come up with the simplest way to do this, although I modified the code slightly (below - doesn't run but is a simplified example of what I was doing). Originally I was wondering if there was a built-in technique that I was missing, but it appears not.

Thanks again

#!/usr/bin/perl -ws use strict; open my $fh, '<', 'file.txt' or die $!; my @lines = ( "this is line 1; foo \n", "this is line 2: bar \n", "this is line 3: foobar \n", ); print "PRINTING FROM FH\n"; working_routine($fh); print "\n\nPRINTING FROM ARRAY\n"; working_routine(\@lines); sub create_iter { my $arg = shift; if (ref $arg eq 'GLOB') { return <$arg>; } elsif (ref $arg eq 'ARRAY') { return shift @$arg; } else { die "Unknown type\n"} } sub working_routine{ my ($data) = @_; my $flag = 0; while(my $line = create_iter($data)){ if($line =~ /matches something/){ next; } elsif($line =~ /matches something else/ and ! $flag){ create_iter($data); my $newline = create_iter($data); dosomethingto($newline); } elsif($line =~ /gotcha/ && $flag){ morework($line); } else{ next; } } }

Replies are listed 'Best First'.
Re^5: Loop through array or filehandle
by Laurent_R (Canon) on Sep 30, 2016 at 11:48 UTC
    The call to create_iter should not be in the while loop, create_iter should be called only once, to obtain the right iterator.

    What should go into the while condition is the call to the iterator returned by create_iter (i.e. $iter->() in my sample code).