Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

opened file being overwritten

by perishowl (Initiate)
on Dec 13, 2012 at 20:23 UTC ( #1008712=perlquestion: print w/ replies, xml ) Need Help??
perishowl has asked for the wisdom of the Perl Monks concerning the following question:

ok this program isnt finished, why isnt the filehandle FILE4 being printed out, instead it just erases or overwrites the file being opened

#!/bin/Perl if (@ARGV < 4) { print ("you need to provide 4 arguments\n\t4th argument is file to + parse"); exit; } openfile(@ARGV); sub openfile { open FILE1,">$_[0]" || die "could not open $_[0]"; open FILE2,">$_[1]" || die "could not open $_[1]"; open FILE3,">$_[2]" || die "could not open $_[2]"; open FILE4,"$_[3]" || die "could not open $_[3]"; } while (my $line = <FILE4>) { print $line; }

Replies are listed 'Best First'.
Re: opened file being overwritten
by GrandFather (Sage) on Dec 13, 2012 at 22:44 UTC

    This is a good time to start always using the three parameter version of open and lexical file handles:

    open my $file4In, '<', $fileName or die "Could not open $filename: $!\ +n";

    Appending In or Out to your file handles helps as a sanity and consistency check.

    You get even more linty goodness if you always use strictures (use strict; use warnings;).

    Note too that showing why an open failed often is at least as useful as showing which open failed.

    True laziness is hard work

      I might add that while it's uncommon to see it done here, checking the return value of print can be useful. Consider this:

      perl -e 'print BADHANDLE "Hello world.\n" or die $!'

      ...output...

      Bad file descriptor at -e line 1.

      ...which is kinda nice information to know.


      Dave

Re: opened file being overwritten
by Generoso (Parson) on Dec 13, 2012 at 22:04 UTC

    This is working fine for me.

    #!/bin/Perl use warnings; if (@ARGV < 4) { print ("you need to provide 4 arguments\n\t4th argument is file to + parse"); exit; } openfile(@ARGV); sub openfile { print $_[3],"\n"; open FILE1,">$_[0]" || die "could not open $_[1]\n"; open FILE2,">$_[1]" || die "could not open $_[2]\n"; open FILE3,">$_[2]" || die "could not open $_[3]\n"; open FILE4,"<$_[3]" || die "could not open $_[4]\n"; while (<FILE4>) { print $_; } }

    Result:

    perl "E:\perl_TK\OpenFiles1.pl" a b c "e:\\territory20100713.sql" Process started >>> Name "main::FILE3" used only once: possible typo at E:\perl_TK\OpenFil +es1.pl line 16. Name "main::FILE1" used only once: possible typo at E:\perl_TK\OpenFil +es1.pl line 14. Name "main::FILE2" used only once: possible typo at E:\perl_TK\OpenFil +es1.pl line 15. e:\\territory20100713.sql -- MySQL dump 10.13 Distrib 5.1.37, for Win32 (ia32) -- -- Host: localhost Database: territory -- ------------------------------------------------------ -- Server version 5.1.37-community /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY +_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO +' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `address` -- DROP TABLE IF EXISTS `address`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `address` ( `ID` int(10) unsigned NOT NULL AUTO_INCREMENT, `Territory` varchar(45) NOT NULL, `Colonia` varchar(45) NOT NULL, `Street` varchar(60) NOT NULL, `Number` varchar(20) NOT NULL, `Lang` varchar(10) NOT NULL, `Notes` varchar(100) NOT NULL, PRIMARY KEY (`ID`) ) ENGINE=InnoDB AUTO_INCREMENT=2302 DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `address` -- LOCK TABLES `address` WRITE; /*!40000 ALTER TABLE `address` DISABLE KEYS */; INSERT INTO `address` VALUES (1,'','1- de Mayo','Av. 1- de Mayo','23 +9','Eng',''),(2,'','1- de /*!40000 ALTER TABLE `address1` ENABLE KEY +S */; UNLOCK TABLES; -- -- Table structure for table `streets` -- DROP TABLE IF EXISTS `streets`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `streets` ( `ID` int(10) unsigned NOT NULL AUTO_INCREMENT, `Territory` varchar(45) NOT NULL, `Colonia` varchar(45) NOT NULL, `Street` varchar(60) NOT NULL, PRIMARY KEY (`ID`) ) ENGINE=InnoDB AUTO_INCREMENT=850 DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `streets` -- LOCK TABLES `streets` WRITE; /*!40000 ALTER TABLE `streets` DISABLE KEYS */; /*!40000 ALTER TABLE `streets` ENABLE KEYS */; UNLOCK TABLES; -- -- Temporary table structure for view `territoy_list` -- DROP TABLE IF EXISTS `territoy_list`; /*!50001 DROP VIEW IF EXISTS `territoy_list`*/; SET @saved_cs_client = @@character_set_client; SET character_set_client = utf8; /*!50001 CREATE TABLE `territoy_list` ( `Territory` varchar(45), `Colonia` varchar(45), `Street` varchar(60), `Number` varchar(20), `Name` varchar(100), `Notes` varchar(100), `Lang` varchar(10), `Pub` varchar(5), `S_ID` varchar(45) ) ENGINE=MyISAM */; SET character_set_client = @saved_cs_client; -- -- Dumping routines for database 'territory' -- /*!50003 CREATE*/ /*!50020 DEFINER=`gene`@`%`*/ /*!50003 FUNCTION `act +uliza`(te CHAR(64), co CHAR -- Dump completed on 2010-07-13 16:17:07 <<< Process finished.
Re: opened file being overwritten
by Anonymous Monk on Dec 13, 2012 at 21:05 UTC

    Why are you opening all the three files before and reading from the 4th file? Also note that that '<' is read and '>' is write mode in the open function.

      #!/bin/Perl use warnings; if (@ARGV < 4) { print ("you need to provide 4 arguments\n\t4th argument is file to + parse"); exit; } $fh = pop(@ARGV); openfile(@ARGV); sub openfile { open FILE1,">$_[0]" || die "could not open $_[0]"; open FILE2,">$_[1]" || die "could not open $_[1]"; open FILE3,">$_[2]" || die "could not open $_[2]"; open FILE4,"<$fh" || die "could not open $fh"; while (<FILE4>) { print $_; } }

      this makes no sense why the FILE4 file handle wont be printed i opened it for reading

        from open,

        If MODE is ">", the file is opened for output, with existing files first being truncated ("clobbered") and nonexisting files newly created. If MODE is ">>", the file is opened for appending, again being created if necessary.
        So, your files $_[0] to $_[3], is been "clobbered", by the ">" mode, while the last one should print out.

        If you tell me, I'll forget.
        If you show me, I'll remember.
        if you involve me, I'll understand.
        --- Author unknown to me

        Another large bug in your code is that due to operator precedence, your dies won't work.

        Basically, open FILE1,">$_[0]" || die "could not open $_[0]" is being interpreted as open FILE1,(">$_[0]" || die "could not open $_[0]")

        $ perl -MO=Deparse -e 'open INP, "<", "hello" || die $!' + open INP, '<', 'hello'; -e syntax OK $ perl -MO=Deparse -e 'open(INP, "<", "hello") || die $!' + die $! unless open INP, '<', 'hello'; -e syntax OK $ perl -MO=Deparse -e 'open INP, "<", "hello" or die "could not open: +$!"' die $! unless open INP, '<', 'hello'; -e syntax OK

        You either need to use the lower-precedence or operator or call the open() function with parentheses.

      the code isnt finished, im planning on writing data to the other 3 files
Re: opened file being overwritten
by 2teez (Priest) on Dec 13, 2012 at 20:30 UTC

    "..why isnt the filehandle FILE4 being printed out.."

    Because when the subroutine finishes the filehandle also closes. Please also check that this in your code open FILE4,"$_[3]" || die "could not open $_[3]"; which has no ">" like the others.
    bart you are right, I missed that.
    Simply using strict and warnings would have indicated the problems.

    If you tell me, I'll forget.
    If you show me, I'll remember.
    if you involve me, I'll understand.
    --- Author unknown to me
      That is just so wrong. FILE1...FILE4 are globals, meaning they won't be closed when the sub exits.

      still not working :(

      #!/bin/Perl use warnings; if (@ARGV < 4) { print ("you need to provide 4 arguments\n\t4th argument is file to + parse"); exit; } $fh = pop(@ARGV); openfile(@ARGV); sub openfile { open FILE1,">$_[0]" || die "could not open $_[0]"; open FILE2,">$_[1]" || die "could not open $_[1]"; open FILE3,">$_[2]" || die "could not open $_[2]"; open FILE4,">$fh" || die "could not open $fh"; while (my $line = <$fh>) { print $line; } }
        i get the warning readline() on unopened filehandle at file.pl line 21. so that would be my while loop while (<$fh>) { print $line; }

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (8)
As of 2016-08-25 20:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    The best thing I ever won in a lottery was:















    Results (362 votes). Check out past polls.