Training, Open Source computer languages
PerlPHPPythonMySQLApache / TomcatTclRubyJavaC and C++LinuxCSS 
Search for:
Home Accessibility Courses Diary The Mouth Forum Resources Site Map About Us Contact
Question regarding %_ ?

Posted by Custard (Custard), 23 December 2004
Hi Guys,

I have a little test program here, which works fine, but I am not sure if there really is a predefined variable in perl called %_
I know there is a $_ and @_ but perldoc perlvar mentions nothing..

In the regex, I use the construct $_{$1}++ which is incrementing an element in a hash.
Which I was surprised worked. (even with strict!).
I wondered whether there was something more mysterious happening here.

Any ideas?

B

Code:
#!/software/perl/5.8.0/bin/perl

use warnings;
use strict;

my $word='casablanca';

# Remove duplicate characters from $word
# ie. casablanca = casbln

$word=~s/(\w)/($_{$1}++)?'':$1/ge;

print "word= ".$word."\n";



Posted by admin (Graham Ellis), 23 December 2004
You code works just as well if you replace %_ with %", or with %demo (but in that latter case you must declare it through "my").

I don't think there's a special has %_ .... and there's certainly not a special %" - I think it's simply that strict allows the special variables en block, just like it allows $a and $b.  

Posted by Custard (Custard), 23 December 2004
Odd though, isn't it, that the docs don't seem to mention it.
@_ and $_ get a mention. Perhaps the criteria for 'un'strictness is <sigil>_

What I was doing was trying to avoid using a temporary hash to squeeze the operation into 1 line.
On second thoughts though, it's a poo idea as %_ needs to be cleared between subsequent uses, and a temp hash would be cleaner.

Code:
#!/usr/local/bin/perl
use warnings;
use strict;

my $word='casablanca';

# Remove duplicate characters from $word
# ie. casablanca = casbln

sub cleanup {
       my $word=shift;
       local %_;
       $word=~s/(\w)/($_{$1}++)?'':$1/ge;

       return $word;
}

print cleanup( 'casablanca' )."\n";
print cleanup( 'greatescape' )."\n";


Produces...
casbln
greatscp

And without the local, produces...
casbln
gretp

Which I guess is what you'd expect from a 'global'.

In case you were wondering, it was part of a bit of code used to decrypt some of the gchq challenge (http://www.gchq.gov.uk/codebreaking/index.html)

B



This page is a thread posted to the opentalk forum at www.opentalk.org.uk and archived here for reference. To jump to the archive index please follow this link.

© WELL HOUSE CONSULTANTS LTD., 2009: Well House Manor • 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01144 1225 708225 • FAX: 01144 1225 707126 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho