What is the easiest way to write to a file using Perl?

I am currently using

system("echo $panel_login $panel_password $root_name $root_pass $port $panel_type >> /home/shared/ftp");

What is the easiest way to do the same with Perl? IE: single line.

+3
source share
9 answers

EDIT (by popular and editable requirement)

http://perldoc.perl.org/functions/open.html

In your case you will have to:

  #21st century perl.
  my $handle;
  open ($handle,'>>','/home/shared/ftp') or die("Cant open /home/shared/ftp");
  print $handle "$panel_login $panel_password $root_name $root_pass $port $panel_type";
  close ($handle) or die ("Unable to close /home/shared/ftp");

Alternatively you can use autodie pragma (like @Chas Owens in the comments). Thus, no verification is required (part or die (...)).

I hope this time everything works out. If so, erases this warning.

Old obsolete way

Use print (but not one liner). Just open your file earlier and get a handle.

open (MYFILE,'>>/home/shared/ftp');
print MYFILE "$panel_login $panel_password $root_name $root_pass $port $panel_type";
close (MYFILE);

http://perl.about.com/od/perltutorials/a/readwritefiles_2.htm

+4

? , ? , , , .

#!/usr/bin/env perl
use strict;
use warnings;

my @values = qw/user secret-password ftp-address/;

open my $fh, '>>', 'ftp-stuff'          # Three argument form of open; lexical filehandle
  or die "Can't open [ftp-stuff]: $!";  # Always check that the open call worked

print $fh "@values\n";     # Quote the array and you get spaces between items for free

close $fh or die "Can't close [ftp-stuff]: $!";
+13

IO:: All, :

use IO::All;
#stuff happens to set the variables
io("/home/shared/ftp")->write("$panel_login $panel_password $root_name $root_pass $port $panel_type");
+8

, File:: Slurp:

use File::Slurp;

append_file("/home/shared/ftp",
    "$panel_login $panel_password $root_name $root_pass ".
    "$port $panel_type\n");

, .

+5
(open my $FH, ">", "${filename}" and print $FH "Hello World" and close $FH) 
    or die ("Couldn't output to file: ${filename}: $!\n");

, ... :

open my $FH, ">", "${filename}" or die("Can't open file: ${filename}: $!\n");
print $FH "Hello World";
close $FH;
+4

psh Psh, Perl.

 psh -c '{my $var = "something"; print $var} >/tmp/out.txt'
0

FileHandle. POD:

use FileHandle;
$fh = new FileHandle ">> FOO"; # modified slightly from the POD, to append
if (defined $fh) {
    print $fh "bar\n";
    $fh->close;
}

- "", :

use FileHandle;
my $fh = FileHandle->new( '>> FOO' ) || die $!;
$fh->print( "bar\n" );
## $fh closes when it goes out of scope
0

:

print "$panel_login $panel_password $root_name $root_pass $port $panel_type" >> io('/home/shared/ftp');

IO:: All , :

use IO::All;
0
-1

Source: https://habr.com/ru/post/1711458/


All Articles