[tpm] Regex question
Richard Dice
rdice at pobox.com
Tue Jul 8 08:40:26 PDT 2008
Here's something that shaves one line off, but it's not particularly pretty
either. Also, it might not work in the context of your larger problem. I
find the most annoying thing in this situation is that $foo and $bar are
both new 'my' variables, and the 'my' declaration syntax is difficult to
work with in other contexts that might create more elegance.
richardmbp:~ rdice$ cat ./test.pl
#!/usr/bin/perl
use warnings;
use strict;
my ($foo, $bar);
($bar = $foo = "ABC-987-01") =~ s/(\w+-\d+)-\d+/$1/;
print "foo = $foo\n";
print "bar = $bar\n";
exit 0;
richardmbp:~ rdice$ perl ./test.pl
foo = ABC-987-01
bar = ABC-987
Alternatively,
richardmbp:~ rdice$ cat ./test2.pl
#!/usr/bin/perl
use warnings;
use strict;
my ($foo, $bar) = ("ABC-987-01");
($bar = $foo) =~ s/(\w+-\d+)-\d+/$1/;
print "foo = $foo\n";
print "bar = $bar\n";
exit 0;
richardmbp:~ rdice$ perl ./test.pl
foo = ABC-987-01
bar = ABC-987
Cheers,
- Richard
On Tue, Jul 8, 2008 at 11:00 AM, Madison Kelly <linux at alteeve.com> wrote:
> Hi all,
>
> I've got a simple problem I often come across, and I've got a way to make
> it work. However, I've always felt there must be a more ... elegant way of
> doing it.
>
> For example, let's say I want to copy a variable and strip a bit off the
> end;
>
> my $foo="ABC-987-01";
> my $bar=$foo;
> $bar=~s/(\w+-\d+)-\d+/$1/;
> # $bar now 'ABC-987'.
>
> That's three lines. Is there a way to do this in one line? Specifically, is
> there a way to assign '$1' to a new variable in one go?
>
> Thanks!
>
> Madi
> _______________________________________________
> toronto-pm mailing list
> toronto-pm at pm.org
> http://mail.pm.org/mailman/listinfo/toronto-pm
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.pm.org/pipermail/toronto-pm/attachments/20080708/76454f2c/attachment.html>
More information about the toronto-pm
mailing list