情報源

  • ActivePerlには、libwww-perlがパッケージとして含まれているので、ローカルの Perl/html/site/lib/lwpcook.html を参照すること。

サンプル

  • TinyProxy.zip
    #!/usr/bin/perl
    # TinyProxy.pl
    # コマンドラインで指定した URI を utf8 としてファイルに保存。
    
    use strict;
    use warnings;
    use utf8;
    use Encode;
    use LWP::UserAgent;
    #use URI::Escape;
    use EscapeSlash;
    
    my $charsetConsole    = 'CP932';
    my $charsetFile        = 'UTF-8';
    
    # ファイル名/パス名として使用できない文字+α
    my %ConvSet = map{ $_ => '%' . uc( unpack( 'H02', $_ ) ) } split( //, '\\/*?|<>:,;% \"' );
    
    @ARGV = map{ decode( $charsetConsole, $_ ); } @ARGV;
    
    my $url = $ARGV[0] or die( "usage: TinyProxy.pl <URI>\n" );
    my $fileNameOut = $url;
    if ( $fileNameOut =~ m#^.*/$# ){
    	$fileNameOut .= 'index.html';
    }
    $fileNameOut =~ s#^\w+://(.*)$#$1#;
    #$fileNameOut = uri_escape_utf8( $fileNameOut );
    $fileNameOut = escapeslash( $fileNameOut, \%ConvSet );
    
    binmode( STDIN,  ":encoding($charsetConsole)" );
    binmode( STDOUT, ":encoding($charsetConsole)" );
    binmode( STDERR, ":encoding($charsetConsole)" );
    
    open( my $OUT, ">:encoding($charsetFile)", encode( $charsetConsole, $fileNameOut ) ) 
    	or die( "$fileNameOut: $!\n" );
    print $OUT getURI( $url );
    close( $OUT );
    
    exit();
    
    # --- Subroutine ---
    sub getURI {
    	my( $URI ) = @_;
    
    	my $ua = LWP::UserAgent->new;
    	my $req = HTTP::Request->new( GET => $URI );
    
    	# send request
    	my $res = $ua->request( $req );
    
    	# check the outcome
    	if ( $res->is_success ){
    		return $res->decoded_content;	# utf8フラグ付テキスト
    	} else {
    		return "Error: " . $res->status_line . "\n";
    	}
    }
    
    # EOF

リンク