in reply to from txt file to array

Use a module for common tasks. Someone has already written and optimized the code, figured out the edge cases, fixes bug reports ...

Path::Tiny is my go-to tool for file handling. To read in lines into an array, use lines(). Chomp if you want, handle encoding if you want.

1193233.txt

Washington New York Louisiana Georgia Texas Iowa

1193233.pl

use strict; use warnings; use feature 'say'; use Path::Tiny; # imports path() my $file = '1193233.txt'; my @list = path( $file )->lines({ chomp => 1 }); say scalar @list . ' items'; say 'item: ' . $_ for @list;

Output:

$ perl 1193233.pl 6 items item: Washington item: New York item: Louisiana item: Georgia item: Texas item: Iowa

Hope this helps!


The way forward always starts with a minimal test.