0

I am trying to append some text to the end of a file in Mac OSX having a .conf extension. I am using the following code to do that:

open NEW , ">>$self->{natConf}";
print NEW "$hostPort = $vmIP";

where

$self->{natConf} = \Library\Preferences\VMware Fusion\vmnet8\nat.conf

So basically this is a .conf file. And even though its not returning any error, but it is not appending anything to the end of the file. I checked all the permissions, and read-write privilege has been provided. Is there anything I am missing here.

matthias krull
  • 4,389
  • 3
  • 34
  • 54
SherinThomas
  • 1,881
  • 4
  • 16
  • 20

2 Answers2

6

First of all use strict and use warnings. This would have thrown errors and warnings for your code.

On Mac OS the delimiter in a path is / like in other unix-like systems not \. To asign a string to a variable use quotation marks. Do not use open(2) but open(3) (the arrow operator does not work in your usage of open anyway) and it is considered bad practice to use bareword filehandlers.

use strict;
use warnings;

# your code here

$self->{natConf} = '/Library/Preferences/VMware Fusion/vmnet8/nat.conf';

# more code here

open my $fh, '>>', $self->{natConf} or die "open failed: $!\n";
print $fh "$hostPort = $vmIP";
close $fh;

# rest of code here
matthias krull
  • 4,389
  • 3
  • 34
  • 54
  • 1
    Good answer. It might be worth explaining the change to using a lexical file handle though. – Quentin Jul 29 '11 at 23:05
  • 1
    You are right. It was issued in this question before http://stackoverflow.com/questions/1479741/why-is-three-argument-open-calls-with-lexical-filehandles-a-perl-best-practice – matthias krull Jul 29 '11 at 23:09
  • Thanks for pointing out the '/' problem, its working now. I am still in the transition period between Windows and Mac, it sucks :( – SherinThomas Jul 29 '11 at 23:27
  • That should almost certainly be `print $fh "$hostPor = $vmIP\n";` (i.e., you want a trialing newline). – Keith Thompson Jul 30 '11 at 02:21
  • 1
    it would be worth either testing the result of `open` by writing `open my $fh, '>>', $self->{natConf} or die "cannot open $self->{natConf}: $!;` or, even simpler, adding `use autodie qw(open);` at the top of the code, which will do the same thing – mirod Jul 30 '11 at 07:58
1

Suffering from buffering? Call close NEW when you are done writing to it, or call (*NEW)->autoflush(1) on it after you open it to force Perl to flush the output after every print.

Also check the return values of the open and print calls. If either of these functions fail, they will return false and set the $! variable.

And I second the recommendation about using strict and warnings.

mob
  • 117,087
  • 18
  • 149
  • 283