CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Writing to a file.

 



michaelalanward
New User

Nov 1, 2010, 7:09 AM

Post #1 of 4 (320 views)
Writing to a file. Can't Post

This now works, that is, it opens my files and sorts it.

But... how do I print to a "file" instead of the screen in perl?

open(IN, "test.txt");
print sort(<IN>);

Any help?

Michael


BillKSmith
Veteran

Nov 1, 2010, 7:57 AM

Post #2 of 4 (312 views)
Re: [michaelalanward] Writing to a file. [In reply to] Can't Post

Good style requires more than a minimum change.

  • Always use strict and warnings.


  • Always close all open files.


  • Always check for errors in open. In more formal work, check print and close for errors also.


  • Always use the three argument form of open (ref perldoc -f open).


  • Always use lexical ($) filehandles.



  • Code
    use strict; 
    use warnings;
    open my $SORTED, '>', 'sorted_test.txt' or die "cannot open ouput file\n";
    open my $IN, '<', 'test.txt' or die "cannot open input file\n";
    print {$SORTED} sort <$IN>;
    close $IN;
    close $SORTED;

    Good Luck,
    Bill


    rovf
    Veteran

    Nov 2, 2010, 2:53 AM

    Post #3 of 4 (306 views)
    Re: [BillKSmith] Writing to a file. [In reply to] Can't Post

    > print {$SORTED} sort <$IN>;

    In this case, the braces around the file handle are not necessary. Is there a particular reason/advantage to use them nevertheless, or do you just have the habit of always using {....}?

    Ronald


    BillKSmith
    Veteran

    Nov 2, 2010, 6:01 AM

    Post #4 of 4 (302 views)
    Re: [rovf] Writing to a file. [In reply to] Can't Post

    Ronald

    Yes, I have developed the habit of using braces around a lexical file handle after reading the recommendation to do just that in the book "Perl Best Practices". I feel that Conway's most compelling reason is:


    Quote
    The braces also convey your intention regarding that variable; namely, that you really did mean it to treated as a filehandle, and didn't just forget a comma.

    Good Luck,
    Bill

     
     


    Search for (options) Powered by Gossamer Forum v.1.2.0

    Web Applications & Managed Hosting Powered by Gossamer Threads
    Visit our Mailing List Archives