Search code examples
fileperlhyperlinkprintf

Print output to a file using Printf (Perl )


I have existing script and part of the script post it here below. I want to print the result to a file. The results are printed on Linux screen session My question how do I print def to a file instead of showing on screen

my $def=printf '/opt/bin/run server=%s os="%s" version=%s application=%s',
    $server, $os, $version, $application;       
print $def."\n" ;

Solution

  • If you look at the documentation for print() you'll see it takes the following forms:

    printf FILEHANDLE FORMAT, LIST
    printf FILEHANDLE
    printf FORMAT, LIST
    print
    

    You are currently using the third form in the list. If you want the output from printf() to go to a file, you can switch to the first form.

    # open a filehandle for your file
    open my $fh, '>', $your_file_name or die "$your_file_name: $!";
    
    printf $fh '/opt/bin/run server=%s os="%s" version=%s application=%s',
           $server, $os, $version, $application;
    

    Note that (like print()) there is no comma between the filehandle and the other arguments.