Home: Perl Programming Help: Intermediate:
Getting Error when I try to write special string to file. Modification of a read-only value attempted



shanaka
New User

Nov 8, 2012, 9:58 AM


Views: 3673
Getting Error when I try to write special string to file. Modification of a read-only value attempted

hi Guys,

I am trying to write string to a file with special characters . I am getting error , "Modification of a read-only value attempted.. "

program is like this,

#!/usr/bin/perl

my $file = "sample.txt";

my $special_string = "%a %t %m %f %s %B %T %n";

print "**".$special_string."\n";

open TXTFILE, ">$file";
printf TXTFILE $special_string."\n";
close TXTFILE;

Out put and error is,


**%a %t %m %f %s %B %T %n
Modification of a read-only value attempted at ./test.pl line 10.

Apriciate anyone can help me to solve the issue.

Thanks,

Shanaka


FishMonger
Veteran / Moderator

Nov 8, 2012, 10:04 AM


Views: 3670
Re: [shanaka] Getting Error when I try to write special string to file. Modification of a read-only value attempted

Why are you using printf?

Use print instead.


shanaka
New User

Nov 8, 2012, 10:16 AM


Views: 3667
Re: [FishMonger] Getting Error when I try to write special string to file. Modification of a read-only value attempted

Thanks, That works.

Do you have any idea why it is not working with printf ? Print is the preffer method to write to a file ?


FishMonger
Veteran / Moderator

Nov 8, 2012, 10:24 AM


Views: 3665
Re: [shanaka] Getting Error when I try to write special string to file. Modification of a read-only value attempted

The printf function expects/requires a format specification AND a list of values. The string you passed could be used as the format specification, but you didn't pass any values. Since your string was intended to be added to the file rather than used as the format for printf, using printf didn't make any sense.


Laurent_R
Veteran / Moderator

Nov 8, 2012, 10:55 AM


Views: 3662
Re: [shanaka] Getting Error when I try to write special string to file. Modification of a read-only value attempted

As a side note, when you have special symbols in a string, you should probably use single quotes rather than double quotes to prevent possible unwanted interpolation such symbols as a sigils (special characters indicating the type of a variable).

For example, it you had:


Code
my $special_string = "%a $m @f ";


you would get warnings and error messages, because the interpreter would think that $m is a scalar variable and @f an array.

You prevent this risk by saying:


Code
my $special_string = '%a $m @f ';