Dharmjeet Kumar
Dharmjeet Kumar

Reputation: 533

Read content of file passed in argument to perl program

I am trying read content of file which I passed as command line argument to perl program

ERROR:

[localhost@dharm myPerlCodes]$ perl data.pl m
FILE NAME IS ==
Could not read from , program halting. at data.pl line 31. 

CODE:

sub get_record {
 # the file_data should be passed in as a parameter
    my $file = shift;
    print "FILE NAME IS == $file\n";
    open(FILE, $file) or die "Could not read from $file, program halting.";
    # read the record, and chomp off the newline
    chomp(my $record = <FILE>);
    close FILE;
    return $record;
}

  $text = &get_record();
  print "text in given file is = $text\n";

What am I doing wrong ?

Upvotes: 1

Views: 593

Answers (3)

AKHolland
AKHolland

Reputation: 4445

If you want to read the content of a file passed as a parameter, you don't need to do any of that. The file will automatically be available in <>. Also, there's no need to use & unless you're dealing with prototypes (and you shouldn't be).

sub get_record {
    chomp( my $record = <> );
    return $record;
}

my $text = get_record();

Upvotes: 0

ysth
ysth

Reputation: 98388

You should be passing the filename to get_record, like:

$text = &get_record(shift @ARGV);

shift inside a subroutine gets arguments passed to the subroutine (@_); only outside of a subroutine does it get command line arguments.

Upvotes: 4

Gabe
Gabe

Reputation: 86708

Outside of a function, shift returns the next parameter to the script, but inside of a function it returns the next parameter.

You need to pass the parameter in to the get_record function: $text = &get_record(shift);

Upvotes: 2

Related Questions