Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Explicit Package?

by catfish1116 (Sexton)
on Feb 07, 2019 at 19:28 UTC ( #1229560=perlquestion: print w/replies, xml ) Need Help??
catfish1116 has asked for the wisdom of the Perl Monks concerning the following question:

Trying to write a program that would read a file in, replace 'fred' with 'Valentine', write to file with .out as extension. I was able to accomplish this, but then I tried modified my code with what was in the book, (Learning Perl), and then got an 'requires explicit package name' for both my in and out files. Below is my code

#! /usr/bin/perl use v5.14; use warnings; ## 2/7/19 my $in = $ARGV[0]; my $out = $in; $^I = ".out"; while (<$in_fn>) { #take one line of input at a time chomp; s/fred/Valentine/gi; print $out_fh $_; }

TIA The catfish

Replies are listed 'Best First'.
Re: Explicit Package?
by toolic (Bishop) on Feb 07, 2019 at 19:39 UTC
    use v5.14;
    That line loads the strict pragma, the same as if you had:
    use strict;
    Refer to use VERSION:
    Similarly, if the specified Perl version is greater than or equal to 5.12.0, strictures are enabled lexically as with use strict
    That is the reason for your error messages. You need to declare your variables with my and open your file handles before using them.
Re: Explicit Package?
by haukex (Canon) on Feb 08, 2019 at 07:29 UTC

    Note that the program you showed is incomplete. It sets $^I, which is the equivalent of the -i command-line switch for in-place editing of files, it operates on the files in @ARGV, and is typically used via the magic <> operator (example). However, by writing <$in_fn> and print $out_fh, it seems you want to use explicit filehandles instead, and in that case, you need to explicitly open those files, for example open my $out_fh, '>', $out or die "$out: $!";. If you do that, then don't also set $^I, as this may have unexpected effects in other parts of the program!

Re: Explicit Package?
by jimpudar (Pilgrim) on Feb 08, 2019 at 01:49 UTC

    You have your answer, but I thought I'd mention you can also write this program as a one liner on the CLI like this:

    perl -wlpe 's/fred/valentine/gi' <in_file >out_file

    πάντων χρημάτων μέτρον έστιν άνθρωπος.

Re: Explicit Package?
by Anonymous Monk on Feb 09, 2019 at 03:57 UTC

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (8)
As of 2019-02-22 20:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    I use postfix dereferencing ...









    Results (118 votes). Check out past polls.

    Notices?