crackerplace
crackerplace

Reputation: 5475

Perl Syntax Error : Sample Program to read a file

I am getting the an error while reading a file and below is the script.

#!/bin/bash
$file = "SampleLogFile.txt";    #--- line 2 
open(MYINPUTFILE,$file);        #--- line 3  
while(<**MYINPUTFILE**>) { 

# Good practice to store $_ value because
# subsequent operations may change it.
my($line) = $_;

# Good practice to always strip the trailing
# newline from the line.
chomp($line);

# Convert the line to upper case.
print "$line" if $line = ~ /sent/;

}
close (MYINPUTFILE);

Output :

PerlTesting_New.ksh[2]: =: not found
PerlTesting_New.ksh[3]: syntax error at line 3 : `(' unexpected

Any idea what the issue is ?

Upvotes: 0

Views: 699

Answers (3)

daotoad
daotoad

Reputation: 27234

Okay, whoever is teaching you to write Perl like this needs to move out of the nineties.

#!/usr/bin/perl

use strict;   # ALWAYS
use warnings; # Also always.  

# When you learn more you can selectively turn off bits of strict and warnings
# functionality  on an as needed basis.


use IO::File; # A nice OO module for working with files.

my $file_name = "SampleLogFile.txt"; # note that we have to declare $file now.

my $input_fh = IO::File->new( $file_name, '<' );  # Open the file read-only using IO::File.

# You can avoid assignment through $_ by assigning to a variable, even when you use <$fh>   

while( my $line = $input_fh->getline() ) { 

    # chomp($line); # Chomping is usually a good idea.  
                    # In this case it does nothing but screw up 
                    # your output, so I commented it out.

    # This does nothing of the sort:
    # Convert the line to upper case.
    print "$line" if $line = ~ /sent/;

}

You can also do this with a one liner:

perl -pe '$_ = "" unless /sent/;'  SampleLogFile.txt

See perlrun for more info on one-liners.

Upvotes: 2

jasonfungsing
jasonfungsing

Reputation: 1655

hmm, your first line : #!/bin/bash

/bin/bash : This is the Bash shell.

You may need to change to

!/usr/bin/perl

Upvotes: 0

parapura rajkumar
parapura rajkumar

Reputation: 24423

Change

#!/bin/bash

to

#!/usr/bin/perl

Otherwise Perl will not be interpreting your script. Change path accordingly as per your system

Upvotes: 5

Related Questions