Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

numbering lines problem

by WisDomSeeKer34 (Sexton)
on Nov 19, 2014 at 13:41 UTC ( [id://1107756]=perlquestion: print w/replies, xml ) Need Help??

WisDomSeeKer34 has asked for the wisdom of the Perl Monks concerning the following question:

I was advised to come here: http://www.linuxquestions.org/questions/showthread.php?p=5271797#post5271797
This is the code:
#!/usr/bin/perl use warnings; for ($x = 1; $x < 10; $x++) { if ($_ =~ /^\d/) {$y = $y + 1;} # if the line does start with a num +ber, ignore it. if ($_ != /^\d/) {print $y.$x;} # if the line doesn't start with nu +mber then print numbers. }
After running it:  perl counting.pl python.txt I get the following error:
Use of uninitialized value $_ in pattern match (m//) at counting.pl line 7.
Use of uninitialized value $_ in pattern match (m//) at counting.pl line 8.
Use of uninitialized value $_ in numeric ne (!=) at counting.pl line 8.
etc.

Purpose of the program is to line numbers according to chapter:
1.
1.1
1.2
2.
2.1
2.2

Replies are listed 'Best First'.
Re: numbering lines problem
by toolic (Bishop) on Nov 19, 2014 at 13:53 UTC
    http://www.linuxquestions.org/questions/showthread.php?p=5271797#post5271797

    Here is a self-contained version. As pan64 noted, you need to get your lines of input from somewhere (this is why $_ is uninitialized). You should just be able to use while (<>) { to read in from your python.txt file.

    use warnings; use strict; my $chap; my $sect; while (<DATA>) { if (/^(\d+)/) { $chap = $1; $sect = 0; } else { $sect++; s/^/$chap.$sect /; } print; } __DATA__ 1. Operators Performing simple arithmetic Operating on bitwise values Comparing values Operating on Boolean values Operating on parts of a container with the slice operator Understanding operator precedence 2. Regular Expressions Using the re module Searching with regular expressions

    See also: perlintro

      Reading your code, it seems so obvious. Thank you.
Re: numbering lines problem
by AnomalousMonk (Archbishop) on Nov 19, 2014 at 14:25 UTC
    if ($_ != /^\d/) {print $y.$x;}    # if the line doesn't start with number then print numbers.

    For future reference, also note that  !~ is "negated match", whereas  != is numeric not-equal, hence the warning. See perlop.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1107756]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (3)
As of 2024-04-25 07:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found