[Melbourne-pm] Writing array data to file with appended information

Jacinta Richardson jarich at perltraining.com.au
Fri Mar 27 02:58:12 PDT 2009

Camillo Pereira wrote:

> This is something that I had tried as well, however, the format of the
> file ends up looking like the following:

> cpploupoi09.my.domain.com.au
>     1cabloupoi08.my.domain.com.au
>     1cacloupoi07.my.domain.com.au
>     1cadloupoi06.my.domain.com.au
>     1caeloupoi05.my.domain.com.au
>     1cafloupoi06.my.domain.com.au
>     1

This suggests that the lines with your domain names on them have newlines still
attached.  You'll need to chomp these newlines off (perldoc -f chomp).  For example:

foreach (@DEVICE_LIST)
    foreach my $t (@critical_device_def)
        my ($site, $device, $flag) = @$t;
        if ($_ =~ m/\G($device)/gc)
            print UPDATE "$_\t1\n" ;

I'm a bit worried about this line:

	if ($_ =~ m/\G($device)/gc)

(which we'd normally write:

	if( m/\G$device/gc )

because you don't seem to be using $1 and matches work on $_ by default).

It's very rare to need to use \G and /g, and I can't think of any way you'd need
to be using it if you're going to call next; straight after a match.  \G allows
you to restart the regular expression from the end of the last successful match
and try to match again from there.  For example this code, with the repeating \G
match line commented out:

my $str = "catsatmat";

foreach (1..3) {
        #if( $str =~ m{\G(\wat)}g ) {
        if( $str =~ m{(\wat)} ) {
                print "$1\n";

gives us:


If we swap the if statements, then we get:


Since you're calling next after your successful match, I'd rewrite your inner
loop to be:

    foreach my $t (@critical_device_def)
        my ($site, $device, $flag) = @$t;
        if ($_ =~ m/$device/)
            print UPDATE "$_\t1\n" ;

I'm assuming that since you don't appear to know what $device matched you don't
need to capture it.  If you've simplified your code a lot, I might be wrong.
I'm also assuming that you won't now need the next, but if you're doing extra
stuff after the if() that you don't want to do on a match, you'll need to put it
back in.

Finally, you define a bunch of patters:

	my @critical_device_def = (
		[AAA => qr{...apb09}    ],
        	[BBB => qr{...avggd09}  ],
	        [CCC => qr{...uytwop09} ],
	        [DDD => qr{...loupoi09} ],

Using fat-comma here - while completely appropriate - may cause some people to
misread this as a number of hash references.  I just recommend to you that you
keep that in mind.

All the best,


   ("`-''-/").___..--''"`-._          |  Jacinta Richardson         |
    `6_ 6  )   `-.  (     ).`-.__.`)  |  Perl Training Australia    |
    (_Y_.)'  ._   )  `._ `. ``-..-'   |      +61 3 9354 6001        |
  _..`--'_..-_/  /--'_.' ,'           | contact at perltraining.com.au |
 (il),-''  (li),'  ((!.-'             |   www.perltraining.com.au   |

More information about the Melbourne-pm mailing list