Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

extracting data from an input file and associated errors

by rakshas (Novice)
on Feb 02, 2012 at 23:28 UTC ( #951557=perlquestion: print w/replies, xml ) Need Help??
rakshas has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I have the following format of data in a text file. I can successfully read it from the file ___________________________________________________________
-rw-r--r-- 1 next users 2153 Jan 1 10:50 mytake_120.115.152.136.csv
I want to extract "" and use it so I wrote the following script.
use strict; use warnings; print "\nEnter the Model 1\n"; my $Model_Name1= <STDIN>; chomp $Model_Name1; open (DATA, "< C:/Perl_Scripts/InputFile.txt"); my @array_of_data = <DATA>; close (DATA); foreach my $line (@array_of_data) { if ( $line =~ m/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\.csv$/g ) { print "Match $1"; } }
As I have said earlier, I want to extract "", hence I am using the regex. It just prints "Match" but also gives an error Use of uninitialized value $_ in pattern match (m//) at C:\Perl_Scripts\ line 31. Any Help will be much appreciated. Regards Vivek

Replies are listed 'Best First'.
Re: extracting data from an input file and associated errors
by jwkrahn (Monsignor) on Feb 02, 2012 at 23:47 UTC
    open (DATA, "< C:/Perl_Scripts/InputFile.txt");

    You should verify that open worked correctly:

    open my $DATA, '<', 'C:/Perl_Scripts/InputFile.txt' or die "Cannot ope +n 'C:/Perl_Scripts/InputFile.txt' because: $!";

    my @array_of_data = <DATA>; close (DATA); foreach my $line (@array_of_data) {

    There is no need to read the entire file into memory first:

    while ( my $line = <$DATA> ) {

    if ( $line =~ m/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\.csv$/g ) { print "Match $1"; }

    The pattern is anchored at the end of the line so the /g option is superfluous.    You are not using capturing parentheses in the pattern so there is nothing in $1 to print out.

Re: extracting data from an input file and associated errors
by chilledham (Friar) on Feb 02, 2012 at 23:42 UTC

    You need to capture the match you want:
    $line =~ m/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\.csv$/g

    The match in your first set of parens will be stored in $1, in the second set of parens in $2, and so on.
    See perldoc perlretut.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://951557]
Approved by toolic
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (11)
As of 2018-06-21 13:16 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (118 votes). Check out past polls.