PDA

View Full Version : placing in array


docock
09-28-2007, 05:15 PM
I'm using the code below to fetch the html code of a page and store it in an array, the code seems a little long though, and the code is written to disk :S
How to shorten the code and place the code in an array without writing to disk?

#!/usr/bin/perl
use CGI;
$q=new CGI;
print "Content-Type: text/html; charset=utf-8\n\n";

use LWP::Simple;
my $url = 'http://www.mysite.com/results?search_query=gees';
my $file = 'booktv.txt';
my $status = getstore($url, $file);

open(FILE, "booktv.txt") or die("Unable to open file");

# read file into an array
@data = <FILE>;

# close file
close(FILE);


All I want to do is read an html file from a certain website, retrieve a line where a certain word occures and place that line into a string.. so if someone can rewrite it...that would be wonderfull (i'm a little noobish at cgi)

FishMonger
09-28-2007, 07:28 PM
In order to put the data into a var instead of the file, you need to use the get() function instead of the getstore(). However, for some reason, the url you posted doesn't return anything when using get, unless I strip it back to its root.

This is how you'd normally get the data into an array instead of the file.
my $url = 'http://www.mysite.com/';
my @data = split(/\n/, get($url) );
Since your posted (search) url returns the site's root home page when using getstore() or getprint() instead of the results of the search, I'd say that there's a redirect happening that the get function doesn't support.

docock
09-30-2007, 12:57 AM
thanks for answering fishmonger..actually that mysite.com part was just for testing.. I've got one more small thing I'm stuck with...

Let's say I've got the code below...How do I display the line of the html file where http://www.yoursite.com occures?

use LWP::Simple;
my $source = get('http://www.w3.org/');
if ($source =~ m|http://(?:www\.)?yoursite\.com/?|) {
print 'Yup';
##### <<<<< display the html line (code) here :confused:
}
else {
print 'Nope';
}

FishMonger
09-30-2007, 02:42 AM
Do you want to display the entire line or just a portion of it?

It would be more efficient to put it into an array instead of the scalar and loop through the array, and it would only take a few additional lines of code. Using a regex against a potentially large string, such as the source of an html page, is not the best choice.

docock
09-30-2007, 11:03 AM
I want to display the whole line, though I haven't got a clue how to do it :S

FishMonger
09-30-2007, 06:19 PM
my @source = split(/\n/, get('http://www.w3.org/') );

my $found;
for ( @source ) {
if ( m|http://www\.nokia\.com/| ) {
$found++;
print 'Yup';
print and last;
}
}
if ( !$found ) {
print 'nope';
}

FishMonger
09-30-2007, 06:22 PM
If you want it more concise/condensed:
my @source = split(/\n/, get('http://www.w3.org/') );
for ( @source ) { print and last if m|http://www\.nokia\.com/|; }