[Chester LUG] Any perl gurus out there ?
Mark Rowlands
mark.rowlands at gmail.com
Mon Nov 24 00:25:36 UTC 2008
Hi Stu,
On Sun, Nov 23, 2008 at 9:15 PM, Stuart Burns
<stuart.james.burns at gmail.com>wrote:
> Hi Everyone,
>
> I am in the process of learning perl but need to finish a program quickly
> but am stuck on something. I am in the process of creating a very simple
> script to create a gallery from random files and urls. To expand a bit, what
> I am trying to do is the following:
>
> read in a file that is in the following format:
>
> 1.jpg|http://www.site1.com/
> 2.jpg|http://www.site2.com/
>
> etc all the way up to 500
>
> Then, randomly choose 20 of the images, and put them into a variable so I
> can spit them out into the format:
>
> <a href="http://www.site1.com/"><Img src="1.jpg"></a>
>
> Can anyone please help me with this. The main problem I am having is
> splitting up the file with the source information in it, as I dont know how
> to read it into an array and split it.
>
Here's a quick example of opening a file, reading in the contents and
splitting via a fixed character.
This opens the file (which contains data in the format you've specified) and
uses the perl split() function on each line, I've not gone any further with
it, like choosing random values - the data ought to be accessible but if
you'd like more let me know:
#!/opt/local/bin/perl -w
my ($file );
my (@stuff );
$file = "input.text"; # This is the file we're going to read in
open (DATA, "$file") || die "Can't open file ($file) $!";
while (my $line = <DATA>) {
chomp($line); # Remove newlines
# Split based on the delimiter |
my ($jpeg, $url) = split(/\|/, $line);
push(@stuff, { jpeg => $jpeg, url => $url } );
}
close (DATA);
# end
What this does is construct an array of hashes, if you pass @stuff through
Data::Dumper:
$VAR1 = {
'url' => 'http://www.site1.com/',
'jpeg' => '1.jpg'
};
$VAR2 = {
'url' => 'http://www.site2.com/',
'jpeg' => '2.jpg'
};
So you'll be able to access any of the values via:
$stuff[$i]{'jpeg'} and $stuff[$i]{'url'} where $x is the array index.
Hope that's of some use.
Mark
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mailman.lug.org.uk/pipermail/chester/attachments/20081124/1edd8c24/attachment.html>
More information about the Chester
mailing list