Hello Monks

I try to learn Perl and want to improve my Perl skills. I've been looking for an answer to my question on the internet, but I didn't find anything yet.

My Script does a lot of "if"query's. So if a condition is right, the script open a filehandle and writes it into a txt file, otherwise the script writes it in another .txt file. This happens in my script 20 times. At the moment I'm opening and closing the Filehandle in every "if" query.

Now I want to ask, whether it is possible, that I open the Filenhandles only once in the whole script? My first solution was writing the Filehandles in a sub routine, but in my opinion I open Filenhadles as much as before.

I hope someone can help me and understand my problem and my bad english.

If a formality is wrong in this forum, please tell me.

An example for my Script is right under this paragraph, but without sub routines and variables for a better understanding.

Thank you for your help

if (`systemctl list-unit-files | grep smb.service`=~ /enabled/){ open (DATEI, ">> path1") or die $!; print DATEI "chkconfig smb: OK\n"; print DATEI "Output:_\n `systemctl list-unit-files | grep smb.serv +ice`\n\n; close (DATEI); } else{ open (DATEI, ">> path2") or die $!; print "chkconfig smb: error\n"; close (DATEI) ###################################################################### +##### if (`systemctl list-unit-files | grep autofs.service`=~ /enabled/){ open (DATEI, ">> path1") or die $!; print DATEI "chkconfig autofs: OK\n"; print DATEI "Output:_\n `systemctl list-unit-files | grep autofs.s +ervice`\n\n; close (DATEI); } else{ open (DATEI, ">> path2") or die $!; print "chkconfig autofs: error\n"; close (DATEI)

In reply to Open Filehandle once by Dunkellbusch

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.