tags:

views:

97

answers:

6

This is some very basic stuff, but I am not able to get what is wrong with it...

test.pl

my $file = "ooout.log";
print $file."\n";
my $file =~ s/\.log//g;
print $file."\n";

output

$ perl test.pl
ooout.log

$

I want to remove the .log at the end. I seem to be doing everything right according to this article. Where did I mess up?

+3  A: 

Try removing my from the replace-line:

$file =~ s/\.log//g;

It seems like you are reinitializing $file.

elusive
thanks for the quick reply!
Lazer
+12  A: 

You're redeclaring my $file -- remove the my prefix to fix this. This would be caught if you started your script with

use strict;
use warnings;

You would have seen:

"my" variable $file masks earlier declaration in same scope at
Evan Carroll
sleske
So `use warnings;` does the same thing as running with `perl -w`? I did not know that.
jnylen
@jnylen: yes, but `use warnings;` is better for a variety of reasons.
Ether
@jnylen: There are subtle differences. See http://perldoc.perl.org/warnings.html and http://perldoc.perl.org/perllexwarn.html
toolic
A: 

Remove the second my, then it will work.

my (somewhat simplified) declares a new variable. You are declaring $file twice, so the second my makes perl forget the value in the first one.

sleske
A: 

You're saying "my $file" in the third line, so you're defining another variable.

Try:

my $file = "ooout.log";
print $file."\n";
$file =~ s/\.log//g;
print $file."\n";
EboMike
A: 

The second my.

Chas. Owens
+7  A: 

Others have pointed out your problem with my.

I'd like to note that your substitution code does not exactly match your spec. It will delete all occurrences of the string .log from your file name.

If you only want to delete .log at the end of your string, don't use the g modifier, and do use the end-of-string anchor $:

use strict;
use warnings;

my $file = "ooout.logical.log";
print "$file\n";
$file =~ s/\.log$//;
print "$file\n";

__END__

ooout.logical.log
ooout.logical
toolic
thanks for pointing that out, @toolic.
Lazer