in reply to Re^2: Read File into array and split
in thread Read File into array and split

I'm not sure how you think split can return a list of dirs for every line, especially since the lines containing "ms" don't contains dirs.

my main goal is to put the hostname in to $client and the dir into @dir and each client starts with ms.

"starts with" implies split probably isn't the right tool.
That you don't have a list of similar items implies split probably isn't the right tool.

Assuming the data is as you showed in in your original post, and assuming that the hostnames are in square brackets and you simply didn't bother to fix your post, the following should do the trick.

my $file = '/scripts/clients'; open(my $fh, '<', $file) or die("Unable to open file \"$file\": $!\n"); my $hostname; my @dirs; while (<$fh>) { chomp; if (/^\[/) { backup($client, \@dirs) if defined($hostname); s/^\[//; s/\]$//; $hostname = $_; @dirs = (); } else { s/^"//; s/"$//; push @dirs, $_; } } backup($client, \@dirs) if defined($hostname);

DATA is a special name. You shouldn't use it. It's bad to use global variables anyway.

Replies are listed 'Best First'.
Re^4: Read File into array and split
by tokyobuddha (Novice) on Mar 07, 2008 at 09:39 UTC
    Let me make this clear this script below is working fine. the only thing is instead of getting dir and hostnames from the script itself i need to read from text file. testfile
    mshostname1
    "/etc/init.d/"
    "/var/logs/"
    mshostname2"
    "/whatever/"
    "/more/"
    This is the working script
    #!/usr/bin/perl my $server = 'nfserver'; my $scp = '/usr/bin/scp'; my $time = localtime; my @mshost1 = ( "msname1", "/local/home/gloob", "/var/spool/cron/crontabs", "/local/home/admin/service.etc" ); my @mshost2 = ( "msname2", "/local/p0/home/gob", "/var/spool/cron/crontabs", "/local/p0/home/admin/service.etc" ); sub backup { my $client = shift; if ($client eq $client) { print "About to tar and scp the following folders: @dir\n\n"; system("ssh", $client, "tar -cvvf $client\.tar.gz @dir"); print("===============================\n"); system("ssh", $client, "scp $client\.tar.gz root\@$server:/export/prod +ucts/backup/"); } else { print "could not backup $client\n"; } } sub get_dir_msd { $client = shift(@mshost1); @dir = @mshost1; print "@dir\n"; print "$client\n"; backup($client); } sub get_dir_msd2 { $client = shift(@mshost2); @dir = @mshost2; print "@dir\n"; print "$client\n"; backup($client); } get_dir_msd("mshost2"); get_dir_msd2("mshost1");

      Let me make this clear this script below is working fine.

      So use it.

      the only thing is instead of getting dir and hostnames from the script itself i need to read from text file.

      I guess you do want to use mine after all.