regexperl

Perl special variables for regex matches


I'd like to use one of perl's special variable to make this snippet a bit less large and ugly:

my $mysqlpass = "mysqlpass=verysecret";
$mysqlpass = first { /mysqlpass=/ } @vars;
$mysqlpass =~ s/mysqlpass=//;

I have looked this info up and tried several special variables ($',$1,$`, etc) to no avail


Solution

  • A s/// will return true if it replaces something.

    Therefore, it is possible to simply combine those two statements instead of having a redundant m//:

    use strict;
    use warnings;
    
    use List::Util qw(first);
    
    chomp(my @vars = <DATA>);
    
    my $mysqlpass = first { s/mysqlpass=// } @vars;
    
    print "$mysqlpass\n";
    
    __DATA__
    mysqluser=notsosecret
    mysqlpass=verysecret
    mysqldb=notsecret
    

    Outputs:

    verysecret
    

    One Caveat

    Because $_ is an alias to the original data structure, the substitution will effect the @vars value as well.

    Alternative using split

    To avoid that, I would inquire if the @vars contains nothing but key value pairs separated by equal signs. If that's the case, then I would suggest simply translating that array into a hash instead.

    This would enable much easier pulling of all keys:

    use strict;
    use warnings;
    
    chomp(my @vars = <DATA>);
    
    my %vars = map {split '=', $_, 2} @vars;
    
    print "$vars{mysqlpass}\n";
    
    __DATA__
    mysqluser=notsosecret
    mysqlpass=verysecret
    mysqldb=notsecret
    

    Outputs:

    verysecret