w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Trying to parse a text file for a string and print a value

You appear to have turned off strict refs to deal with an error something along these lines that you may have received:

Can't use string ("Ask") as a symbol ref while "strict refs" in
use ...

For reference to your call to opendir: http://perldoc.perl.org/functions/opendir.html

Try using a new variable to make a filehandle for the dir with opendir.

So this line:

opendir $DIR, '.' or die "opendir .: $!

Could be something more like

opendir(my $current_directory, '.') or die $!;

Give or take some stylistic choices. This will make $current_directory its own filehandle, instead of trying to use the previously declared $DIR.

In Perl, you never really want to disable 'use strict' it can lead you to ruin!

Here's a version of your script that for me found what I was looking for based on a file containing the following:

phone: 18008000
phone: 18008001
not phone
phone: 18008002

The script:

use strict;
use warnings;

my $calls_dir = "ask/";

opendir(my $search_dir, $calls_dir) or die "$!
my @files = grep /.txt$/i, readdir $search_dir;
closedir $search_dir;
print "Got ", scalar @files, " files

my %seen = ();
foreach my $file (@files) {
    my $current_file = $calls_dir . $file;
    open my $FILE, '<', $current_file or die "$file: $!
    while (<$FILE>) {
        if (/^phone:s*(.*)
?$/i) {
            $seen{$1} = 1;
            foreach my $addr (sort keys %seen) {
                print "$addr
    close $FILE;

Hopefully this will get you where you want to go. Don't turn off use strict while you're learning Perl! (or ever :D)

© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.