Flubb has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks, I have a script which gets the amount of free space on the HDD , goes to a file and finds a line with the name of that particular computer on it, and then swaps out the last known free space with the new variable.
The line to be replaced looks like this:
 graphv[1]=["S-PC228WXP","74GB"]
The "74GB" section is the bit that gets replaced with the new amount.
My script works, but complains at the substitution point, that I've got an invalid range in the regex. I know it's a horrible script and probably needs help, but I can't work out how to stop it interpreting the variable at the substitution point.
Many thanks
#!/usr/local/bin/perl -w use File::stat; use strict; use Tie::File; use Env qw(COMPUTERNAME); my($s3) = "d:\\softdev"; my($testdata)= "d:\\softdev\\t.html"; my($graphdata)= "d:\\softdev\\t.html"; my(@testarray); my(@grapharray); chop (my($hostname)= `hostname`); my($COMPUTERNAME) = uc($hostname); my($line); my($newgb); my($grapharray); my($softdev) = "d:\\softdev"; my(@diskspace); my ($new); my($reallynewgb); my($newline); spacecheck(); graphsub(); sub spacecheck { my(@testarray); my $dircheck = "HDDSpace"; my ($meg); die "Cannot perform diskspace check" unless (system("dir $softdev > HD +DSpace")==0); tie @testarray, 'Tie::File', "$dircheck"; for(@testarray) { if(/bytes free/) { @testarray = split /\s+/, $_; $testarray[3] =~ s/,//g; $meg = 1024*1024*1024; $newgb = int ($testarray[3]/$meg); print "Diskspace left: " ."$newgb" . "MB\n"; my($reallynewgb) = "$newgb"."GB"; } } undef @testarray; untie @testarray; } sub graphsub { print "$newgb is gb\n"; print "Going to server!\n"; chdir $s3 or die "Cannot change $!\n"; print "going to tie the file\n"; tie @grapharray, 'Tie::File', "$graphdata", or die "Cannot open $g +raphdata $!\n"; #this opens the file print "$COMPUTERNAME is computername\n putting in $newgb as th +e new GB\n"; foreach(@grapharray) { if ($_ =~ m/$COMPUTERNAME/) { $line = $_; $newline = $_; print "Line is $line\n"; print "Newline is $newline\n"; my($reallynewgb) = $newgb."GB"; print "line is: $line and $reallynewgb is GB\n"; $newline =~ ($_ =~ (s/(\d|\d\d|\d\d\d)GB/$reallyne +wgb/)); print "$newline is the newnewline\n"; print "$line is the new line\n"; print "$_ line in \n"; s/$newline/$line/; print "$line\n"; } } untie @grapharray; #finish the array :) }

Replies are listed 'Best First'.
Re: Regex and Substitute issues
by moritz (Cardinal) on Jun 23, 2008 at 11:53 UTC
    s/$newline/$line/;

    I think that's the offending line. $newline is parsed as a regex here, but it's an arbitrary string. Use s/\Q$newline\E/$line/ instead. (Or clean up your script.

    BTW (\d|\d\d|\d\d\d) can be expressed as (\d{1,3}).

      Thanks moritz, that was just the ticket!