Reputation: 93
First off, let me tell you that I have worked very little with Arrays and never with Hashes. Also, Perl is not my strongest scripting language. I come from a background in shell scripting.
That said, I have this in a Perl script:
$monitored_paths = { '/svn/test-repo' => 'http://....list.txt' };
The URL points to a file which contains a list of paths like this:
/src/cpp
/src/test
/src/test2
The objective is to replace the URL with the contents:
$monitored_paths = {'svn/test-repo' => '/src/cpp', '/src/test', '/src/test2'}
What would be the best way to achieve this? Thanks!
Sam
Upvotes: 0
Views: 458
Reputation: 4800
There is an error in the premise of your question, because this line:
$monitored_paths = {'svn/test-repo' => '/src/cpp', '/src/test', '/src/test2'}
is the equivalent of either of these:
$monitored_paths = {'svn/test-repo' => '/src/cpp', '/src/test' => '/src/test2'}
$monitored_paths = {'svn/test-repo', '/src/cpp', '/src/test', '/src/test2'}
What you really want is:
$monitored_paths = {'svn/test-repo' => ['/src/cpp', '/src/test', '/src/test2']}
where [] denotes an array reference. You create an array reference like this:
my $arrayref = [1, 2, 3]; # called an "anonymous array reference"
or like this:
my @array = (1, 2, 3);
my $arrayref = \@array;
You want something such as:
$monitored_paths = { '/svn/test-repo' => 'http://....list.txt' }
foreach my $key (keys %$monitored_paths) {
next if ref $monitored_paths{$key} eq 'ARRAY'; # skip if done already
my @paths = get_paths_from_url($key);
$monitored_paths->{$key} = \@paths; # replace URL with arrayref of paths
}
replacing get_paths_from_url with your URL-fetching and parsing function (using LWP or whatever...since that was not really part of your question I assume you already know how to do that). If you write your function get_paths_from_url to return an array reference in the first place instead of an array, you can save a step and write $monitored_paths->{$key} = get_paths_from_url($key)
instead.
Upvotes: 1
Reputation: 22705
use LWP;
foreach (keys %monitored_paths)
{
my $content = get($monitored_paths{$_});# Perform error checking
$monitored_paths_final {$_} = join(",",split("\n",$content));
}
Upvotes: 0
Reputation: 23065
use LWP::Simple;
my $content = get($url); ## do some error checking
$monitored_paths = {'svn/test-repo' => [split( "\n", $content)]}
Upvotes: 0
Reputation: 1384
If you want to read from the file and add each path to the array you could do something like:
use strictures 1;
my $monitored_paths = {};
open( my $FILE, '<', '/path/to/file' ) or die 'Unable to open file '. $!;
while($FILE){
push @{ $monitored_paths->{'svn/test-repo'} }, $_;
}
Upvotes: 0