perlsubroutinespecial-variables

Perl special variable "@_" in a subroutine not working


This script rips out the urls from a downloaded webpage. I had some trouble with this script - when I use the "my $csv_html_line = @_ ;" and then print out the "@html_LineArray" - it just prints out "1's". When I replace the "my $csv_html_line = @_ ;" with "my $csv_html_line = shift ;" the script works fine. I do not know what the difference is betweeh the "= @_" and shift - becuase I thought that without specifying something, in a subroutine, shift shift froms "@_".

#!/usr/bin/perl
use warnings;
use strict ;

sub find_url {
    my $csv_html_line = @_ ;
    #my $csv_html_line = shift ;
    my @html_LineArray = split("," , $csv_html_line ) ;
    print "@html_LineArray\n" ;
    #foreach my $split_line(@html_LineArray) {
    #    if ($split_line =~ m/"adUrl":"(http:.*)"/) {
    #        my $url = $1;
    #        $url =~ tr/\\//d;
    #        print("$url\n")  ;
    #    }
    #}
}



my $local_file = "@ARGV" ;
open(my $fh, '<', "$local_file") or die "cannot open up the $local_file $!" ;
while( my $html_line = <$fh>) {
    #print "$html_line\n";
    find_url($html_line) ;
}

This is what the above prints out.

1
1
1
1
1
1
1
1
1
1
1
1

This works fine - it uses the shift instead of "@_"

#!/usr/bin/perl
use warnings;
use strict ;

sub find_url {
    #my $csv_html_line = @_ ;
    my $csv_html_line = shift ;
    my @html_LineArray = split("," , $csv_html_line ) ;
    #print "@html_LineArray\n" ;
    foreach my $split_line(@html_LineArray) {
        if ($split_line =~ m/"adUrl":"(http:.*)"/) {
            my $url = $1;
            $url =~ tr/\\//d;
            print("$url\n")  ;
        }
    }
}



my $local_file = "@ARGV" ;
open(my $fh, '<', "$local_file") or die "cannot open up the $local_file $!" ;
while( my $html_line = <$fh>) {
    #print "$html_line\n";
    find_url($html_line) ;
}

Solution

  • It's

    my ($csv_html_line) = @_ ;
    

    The way you wrote the code you evaluated @_ in scalar context and got its length (number of elements). As you noted,

    my $csv_html_line = shift;
    

    works because the shift operator takes a list and removes and returns the first element as a scalar.