如何从Perl中的变量值中删除$字符?

时间:2013-07-14 18:44:05

标签: perl

假设我有一个变量,该变量被赋予一些包含$字符的字符串。例如:

$a="$192.168.1.1";

我必须使用Perl删除$个字符。文本将隐式分配给变量。

怎么做?

$v =~ s/\$//;  # this does not work for me :(




$="$192.168.1.1"
$ips =~ substr$ips ,1);
 push (@planets,  $ips 

2 个答案:

答案 0 :(得分:7)

首先请注意,您不能使用双引号分配给$a,因为$192将被插值,几乎肯定会失败。

您应该始终任何 Perl代码中使用use strict;use warnings;。如果您确实尝试过这项任务,它会发出警告。

因此,如果您的作业是明确的,请改为使用单引号:

my $a = '$192.168.1.1';

然后,如果$ 总是,那么只需使用substr - 它比使用正则表达式要快得多。

$a = substr($a, 1);

如果你不确定$会在那里,那么你在上面使用的行可以正常工作,如果你将它应用于正确的变量:

$a =~ s/\$//;

或者:

$a =~ tr/$//d;

答案 1 :(得分:4)

这是半工作和工作代码。

半的工作

$ cat x1.pl | so
#!/usr/bin/env perl
use strict;
use warnings;

my $a = "$192.168.1.1";
print "$a\n";
$a =~ s/\$//;
print "$a\n";

$ perl x1.pl | so
Use of uninitialized value $192 in concatenation (.) or string at x1.pl line 5.
.168.1.1
.168.1.1
$

工作

$ cat x2.pl | so
#!/usr/bin/env perl
use strict;
use warnings;

my $a = '$192.168.1.1';
print "$a\n";
$a =~ s/\$//;
print "$a\n";

$ perl x2.pl | so
$192.168.1.1
192.168.1.1
$ 

在您学习Perl时,始终使用use strict;use warnings;(前20年左右是最难的)。

如果您的代码仍然无效,则需要显示等效的SSCCE(Short, Self-Contained, Correct Example)代码和示例输出,但它绝对应包含use strict;use warnings;。< / p>