www.webdeveloper.com
Results 1 to 3 of 3

Thread: My Loop Needs some Serious Help

  1. #1
    Join Date
    May 2009
    Posts
    129

    My Loop Needs some Serious Help

    Hi all,

    I am 100% new to Perl but do have some PHP knowledge. I'm trying to create a quick script that will take the @url vars and save it to a .txt file. The problem that I'm having is that it's saving the url again everytime it runs through the loop which is super annoying. So when the loop runs, it'll look like this.

    url1.com
    url1.com url2.com
    url1.com url2.com url3.com

    What I would like it to look like is just a plain and simple..

    url1.com
    url2.com
    url3.com

    Here is my code. If anyone can help, I would appreciate it SO SO much!

    PHP Code:
    #!/usr/bin/perl
    use strict;
    use 
    warnings;

    my $file "data.rdf.u8";
    my @urls;

    open(my $fh"<"$file) or die "Unable to open $file\n";

    while (
    my $line = <$fh>) {
        if (
    $line =~ m/<(?:ExternalPage about|link r:resource)="([^\"]+)"\/?>/) {
            push @urls, $1;
        }
    open (FH, ">>my_urls.txt") or die "$!";
    print FH "@urls ";
    close(FH);


    }

    close $fh; 

  2. #2
    Join Date
    Mar 2009
    Posts
    452
    i too don't know perl at all but do some PHP, i found a link maybe useful for you http://perl.about.com/od/perltutorials/a/perlpush.htm

  3. #3
    Join Date
    Oct 2007
    Location
    Vienna, Austria
    Posts
    387
    What you do is:

    for each line { add the line to @urls; print the whole @urls array }

    Of course you end up with
    url1
    url1 url2
    url1 url2 url3

    The simplest thing were to move the printing outside the loop.
    Code:
    #!/usr/bin/perl
    use strict;
    use warnings;
    
    my $file = "data.rdf.u8";
    my @urls;
    
    open(my $fh, "<", $file) or die "Unable to open $file\n";
    
    while (my $line = <$fh>) {
        if ($line =~ m/<(?:ExternalPage about|link r:resource)="([^\"]+)"\/?>/) {
            push @urls, $1;
        }
    }
    
    open (FH, ">>my_urls.txt") or die "$!";
    print FH "@urls ";
    close(FH);
    
    close $fh;
    In that case, you can probably just open it for writing (>) not for appending (>>). But that depends on whether you want to preserve what there was before running the script or not.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles