Welcome to Dream.In.Code
Become an Expert!

Join 149,520 Programmers for FREE! Get instant access to thousands of experts, tutorials, code snippets, and more! There are 1,399 people online right now. Registration is fast and FREE... Join Now!




Basic Perl Questions/Answers?

2 Pages V  1 2 >  
Reply to this topicStart new topic

Basic Perl Questions/Answers?

josephman1988
7 Jul, 2007 - 09:53 AM
Post #1

New D.I.C Head
*

Joined: 7 Jul, 2007
Posts: 11


My Contributions
Hi,

The reason for the topic title is because I'l be asking various questions in the same thread over a period of time, easier then making a million threads!

Anyway, I'm having a problem with one of my scripts.

What I want to do is read a file that the user inputs.
E.g - stats.txt will open the file.

However, what i want to do, is that if the user doesn't enter a extension of .txt it will automatically add it.

My attempt:

CODE
my $file = <STDIN>;
open(READFILE, "$file") || die "No File Found";

if ($file !~ m/.txt$/)
{
$file .= ".txt";
} else {
print "There was already a .txt filename\n";
}

my $i = 0;
while (<READFILE>)
{
$i++;
}
print ("There are " . $i . " Lines in " . $file);
close(READFILE);
However, this doesn't work. =[

Any help is greatly appreciated.
User is offlineProfile CardPM
+Quote Post

KevinADC
RE: Basic Perl Questions/Answers?
7 Jul, 2007 - 10:16 AM
Post #2

D.I.C Head
Group Icon

Joined: 23 Jan, 2007
Posts: 238



Thanked: 6 times
Dream Kudos: 50
My Contributions
Saying "it doesn't work" is not very helpful. Post any error messages or warnings the script outputs or describe what the script does do.

In your case I see one problem right away:

CODE
my $file = <STDIN>;


$file will end with an input terminator, probably a newline, so it will not be able to open a file named "file.txt\n" which your die statment should have caught and echoed back an error. You need to use chomp() on your input:

CODE
chomp(my $file = <STDIN>);


from now on, start all your perl script with these two pragmas:

CODE
use strict;
use warnings;


and you can add this one for good measure:

CODE
use diagnostics;


The first two are very important, especially for new perl coders. The third one dplays very verbose messages and is sometimes more useful than the brief messages that perl outputs by default.

If your perl resource material did not mention the need to chomp() input, I would stop using it.

Besides all that, your script looks like it should work once the chomp() is added.

Kevin
User is offlineProfile CardPM
+Quote Post

josephman1988
RE: Basic Perl Questions/Answers?
7 Jul, 2007 - 10:40 AM
Post #3

New D.I.C Head
*

Joined: 7 Jul, 2007
Posts: 11


My Contributions
Apologies.

Whether we have the:

CODE
if ($file !~ m/.txt$/)
{
$file .= ".txt";
} else {
print "There was already a .txt filename\n";
}


Or not, we can still bring up the .txt document by typing in the extension.

After adding the warnings, strict and diagnostics, and then running the script again.Without supplying the extension i am faced with the following error.
(BTW, I am using the command line);

IPB Image

With the code being ultimately altered to:

CODE
#!/usr/bin/perl
use strict;
use warnings;
use diagnostics;

chomp(my $file = <STDIN>);
open(READFILE, "$file") || die "Dead";

if ($file !~ m/.txt$/)
{
$file .= ".txt";
} else {
print "There was already a .txt filename\n";
}

my $i = 0;
while (<READFILE>)
{
$i++;
}
print ("There are " . $i . " Lines in " . $file . "\n");
close(READFILE);


User is offlineProfile CardPM
+Quote Post

KevinADC
RE: Basic Perl Questions/Answers?
7 Jul, 2007 - 10:51 AM
Post #4

D.I.C Head
Group Icon

Joined: 23 Jan, 2007
Posts: 238



Thanked: 6 times
Dream Kudos: 50
My Contributions
change this line:

CODE
open(READFILE, "$file") || die "Dead";


to:

CODE
open(READFILE, "$file") or die "Can't open file '$file': $!";


$! stores the operating system error message, which you will need to see why the file is not being opened by the perl script. Where are you learning perl from? This is quite useless:

die "Dead";

I hope your perl resource material did not suggest using that useless construct. You should also use the lower precedence "or" for program flow control instead of "||".


User is offlineProfile CardPM
+Quote Post

josephman1988
RE: Basic Perl Questions/Answers?
7 Jul, 2007 - 11:07 AM
Post #5

New D.I.C Head
*

Joined: 7 Jul, 2007
Posts: 11


My Contributions
I used the:

die "Dead";

As i didn't think it mattered what i actually printed at this time?
Oh so i understand why the $! is now used, thanks.

The error message is now:

CODE
stats
Can't open file 'stats': No such file or directory at
        C:\DOCUME~1\J-Man\LOCALS~1\Temp\dir798.tmp\RF.pl line 7, <STDIN> line 1
(#1)
    (S inplace) The implicit opening of a file through use of the <>
    filehandle, either implicitly under the -n or -p command-line
    switches, or explicitly, failed for the indicated reason.  Usually this
    is because you don't have read permission for a file which you named on
    the command line.

Uncaught exception from user code:
        Can't open file 'stats': No such file or directory at C:\DOCUME~1\J-Man\
LOCALS~1\Temp\dir798.tmp\RF.pl line 7, <STDIN> line 1.
at C:\DOCUME~1\J-Man\LOCALS~1\Temp\dir798.tmp\RF.pl line 7


This post has been edited by josephman1988: 7 Jul, 2007 - 11:08 AM
User is offlineProfile CardPM
+Quote Post

KevinADC
RE: Basic Perl Questions/Answers?
7 Jul, 2007 - 11:26 AM
Post #6

D.I.C Head
Group Icon

Joined: 23 Jan, 2007
Posts: 238



Thanked: 6 times
Dream Kudos: 50
My Contributions
The problem is that file "stat" can't be found. I would think you would want to check/add the "txt" extension before trying to open the file. Also, the file has to be in the same directory as the script if you don't use a path to the file when you try and open the file.

I'll check back later, I've got stuff to do.
User is offlineProfile CardPM
+Quote Post

josephman1988
RE: Basic Perl Questions/Answers?
7 Jul, 2007 - 11:30 AM
Post #7

New D.I.C Head
*

Joined: 7 Jul, 2007
Posts: 11


My Contributions
Omg, trust it to be a simple snippet of code being added in the wrong place.

Thanks for the help mate.

Appreciate your time. =]
User is offlineProfile CardPM
+Quote Post

josephman1988
RE: Basic Perl Questions/Answers?
7 Jul, 2007 - 01:11 PM
Post #8

New D.I.C Head
*

Joined: 7 Jul, 2007
Posts: 11


My Contributions
If i wanted to put in another feature, where the user has to input a filename with only letters, would i have to put this in the same code block or a separate on?

For E.g -
until ($file =~ m/[a-zA-Z])

How would i repeat this process until the user inputs a valid set of characters?
Would i use a 'redo LOOP:' method or what?

Thanks.
User is offlineProfile CardPM
+Quote Post

KevinADC
RE: Basic Perl Questions/Answers?
7 Jul, 2007 - 10:07 PM
Post #9

D.I.C Head
Group Icon

Joined: 23 Jan, 2007
Posts: 238



Thanked: 6 times
Dream Kudos: 50
My Contributions
QUOTE(josephman1988 @ 7 Jul, 2007 - 02:11 PM) *

If i wanted to put in another feature, where the user has to input a filename with only letters, would i have to put this in the same code block or a separate on?

For E.g -
until ($file =~ m/[a-zA-Z])

How would i repeat this process until the user inputs a valid set of characters?
Would i use a 'redo LOOP:' method or what?

Thanks.


Well, there are a number of ways to do something like this. You sort of have the correct concept. The regexp is not correct though because it is only checking to see if there is at least one of those characters any where in the string. To check the entire string you have to use string anchors:

^ (beginning of string)
$ (end of string)

CODE
until ($file =~ m/^[a-zA-Z]{10,20}$)


the {10,20} checks for a min and max length.


User is offlineProfile CardPM
+Quote Post

josephman1988
RE: Basic Perl Questions/Answers?
8 Jul, 2007 - 04:50 AM
Post #10

New D.I.C Head
*

Joined: 7 Jul, 2007
Posts: 11


My Contributions
That worked like a charm. =]

Last question on this matter I promise!

Say the text file being read has 2 paragraphs, being separated by 2 newlines.

How would I count the paragraphs in the text file and print the results?

icon_up.gif
User is offlineProfile CardPM
+Quote Post

KevinADC
RE: Basic Perl Questions/Answers?
8 Jul, 2007 - 01:59 PM
Post #11

D.I.C Head
Group Icon

Joined: 23 Jan, 2007
Posts: 238



Thanked: 6 times
Dream Kudos: 50
My Contributions
One way is to change the input record seperator to "\n\n"

CODE
use strict;
use warnings;

{
   local $/ = "\n\n";
   my @paragraphs  = <DATA>;
   print scalar @paragraphs;
}



__DATA__
this is the first paragraph
this is the first paragraph
this is the first paragraph
this is the first paragraph

this is the second paragraph
this is the second paragraph
this is the second paragraph
this is the second paragraph

User is offlineProfile CardPM
+Quote Post

josephman1988
RE: Basic Perl Questions/Answers?
9 Jul, 2007 - 01:41 AM
Post #12

New D.I.C Head
*

Joined: 7 Jul, 2007
Posts: 11


My Contributions
I managed to find a simple way.
CODE
$p++ if (m/^$/);


But now I'm really confused?
I want to count characters in the file, whitespace and a-z only.
As well as words and sentences.

So i tried the following for words

$c++ if (m/^\w+\s+/);
- This actually counts the lines excluding paragraphs -

Don't know how to count single characters and words though?



User is offlineProfile CardPM
+Quote Post

2 Pages V  1 2 >
Fast ReplyReply to this topicStart new topic
Time is now: 1/7/09 08:20PM

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live Help!

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month