code
stringlengths
2
1.05M
repo_name
stringlengths
5
101
path
stringlengths
4
991
language
stringclasses
3 values
license
stringclasses
5 values
size
int64
2
1.05M
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Copyright [2016-2019] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =cut =head1 CONTACT Please email comments or questions to the public Ensembl developers list at <http://lists.ensembl.org/mailman/listinfo/dev>. Questions may also be sent to the Ensembl help desk at <http://www.ensembl.org/Help/Contact>. =cut =head1 NAME =head1 SYNOPSIS =head1 DESCRIPTION =head1 METHODS =cut package Bio::EnsEMBL::IdMapping::InternalIdMapper::EnsemblTranscriptGeneric; use strict; use warnings; no warnings 'uninitialized'; use Bio::EnsEMBL::IdMapping::InternalIdMapper::BaseMapper; our @ISA = qw(Bio::EnsEMBL::IdMapping::InternalIdMapper::BaseMapper); use Bio::EnsEMBL::Utils::Exception qw(throw warning); use Bio::EnsEMBL::Utils::ScriptUtils qw(path_append); # # basic mapping # sub init_basic { my $self = shift; my $num = shift; my $tsb = shift; my $mappings = shift; my $transcript_scores = shift; $self->logger->info("Basic transcript mapping...\n", 0, 'stamped'); $mappings = $self->basic_mapping($transcript_scores, "transcript_mappings$num"); $num++; my $new_scores = $tsb->create_shrinked_matrix($transcript_scores, $mappings, "transcript_matrix$num"); return ($new_scores, $mappings); } # # handle cases with exact match but different translation # sub non_exact_translation { my $self = shift; my $num = shift; my $tsb = shift; my $mappings = shift; my $transcript_scores = shift; $self->logger->info("Exact Transcript non-exact Translation...\n", 0, 'stamped'); unless ($transcript_scores->loaded) { $tsb->different_translation_rescore($transcript_scores); $transcript_scores->write_to_file; } $mappings = $self->basic_mapping($transcript_scores, "transcript_mappings$num"); $num++; my $new_scores = $tsb->create_shrinked_matrix($transcript_scores, $mappings, "transcript_matrix$num"); return ($new_scores, $mappings); } # # reduce score for mappings of transcripts which do not belong to mapped # genes # sub mapped_gene { my $self = shift; my $num = shift; my $tsb = shift; my $mappings = shift; my $transcript_scores = shift; my $gene_mappings = shift; $self->logger->info("Transcripts in mapped genes...\n", 0, 'stamped'); unless ($transcript_scores->loaded) { $tsb->non_mapped_gene_rescore($transcript_scores, $gene_mappings); $transcript_scores->write_to_file; } $mappings = $self->basic_mapping($transcript_scores, "transcript_mappings$num"); $num++; my $new_scores = $tsb->create_shrinked_matrix($transcript_scores, $mappings, "transcript_matrix$num"); return ($new_scores, $mappings); } # # rescore by penalising scores between transcripts with different biotypes # sub biotype { my $self = shift; my $num = shift; my $tsb = shift; my $mappings = shift; my $transcript_scores = shift; $self->logger->info( "Retry with biotype disambiguation...\n", 0, 'stamped' ); unless ( $transcript_scores->loaded() ) { $tsb->biotype_transcript_rescore($transcript_scores); $transcript_scores->write_to_file(); } my $new_mappings = $self->basic_mapping( $transcript_scores, "transcript_mappings$num" ); $num++; my $new_scores = $tsb->create_shrinked_matrix( $transcript_scores, $new_mappings, "transcript_matrix$num" ); return ( $new_scores, $new_mappings ); } # # selectively rescore by penalising scores between transcripts with # different internalIDs # sub internal_id { my $self = shift; my $num = shift; my $tsb = shift; my $mappings = shift; my $transcript_scores = shift; $self->logger->info("Retry with internalID disambiguation...\n", 0, 'stamped'); unless ($transcript_scores->loaded) { $tsb->internal_id_rescore($transcript_scores); $transcript_scores->write_to_file; } $mappings = $self->basic_mapping($transcript_scores, "transcript_mappings$num"); $num++; my $new_scores = $tsb->create_shrinked_matrix($transcript_scores, $mappings, "transcript_matrix$num"); return ($new_scores, $mappings); } # # handle ambiguities between transcripts in single genes # sub single_gene { my $self = shift; my $num = shift; my $tsb = shift; my $mappings = shift; my $transcript_scores = shift; $self->logger->info("Transcripts in single genes...\n", 0, 'stamped'); unless ($transcript_scores->loaded) { $transcript_scores->write_to_file; } $mappings = $self->same_gene_transcript_mapping($transcript_scores, "transcript_mappings$num"); $num++; my $new_scores = $tsb->create_shrinked_matrix($transcript_scores, $mappings, "transcript_matrix$num"); return ($new_scores, $mappings); } # # modified basic mapper that maps transcripts that are ambiguous within one gene # sub same_gene_transcript_mapping { my $self = shift; my $matrix = shift; my $mapping_name = shift; # argument checks unless ($matrix and $matrix->isa('Bio::EnsEMBL::IdMapping::ScoredMappingMatrix')) { throw('Need a Bio::EnsEMBL::IdMapping::ScoredMappingMatrix.'); } throw('Need a name for serialising the mapping.') unless ($mapping_name); # Create a new MappingList object. Specify AUTO_LOAD to load serialised # existing mappings if found my $dump_path = path_append($self->conf->param('basedir'), 'mapping'); my $mappings = Bio::EnsEMBL::IdMapping::MappingList->new( -DUMP_PATH => $dump_path, -CACHE_FILE => "${mapping_name}.ser", -AUTO_LOAD => 1, ); # checkpoint test: return a previously stored MappingList if ($mappings->loaded) { $self->logger->info("Read existing mappings from ${mapping_name}.ser.\n"); return $mappings; } my $sources_done = {}; my $targets_done = {}; # sort scoring matrix entries by descending score my @sorted_entries = sort { $b->score <=> $a->score || $a->source <=> $b->source || $a->target <=> $b->target } @{ $matrix->get_all_Entries }; while (my $entry = shift(@sorted_entries)) { # $self->logger->debug("\nxxx4 ".$entry->to_string." "); # we already found a mapping for either source or target yet next if ($sources_done->{$entry->source} or $targets_done->{$entry->target}); #$self->logger->debug('d'); my $other_sources = []; my $other_targets = []; my %source_genes = (); my %target_genes = (); if ($self->ambiguous_mapping($entry, $matrix, $other_sources, $other_targets)) { #$self->logger->debug('a'); $other_sources = $self->filter_sources($other_sources, $sources_done); $other_targets = $self->filter_targets($other_targets, $targets_done); $source_genes{$self->cache->get_by_key('genes_by_transcript_id', 'source', $entry->source)} = 1; $target_genes{$self->cache->get_by_key('genes_by_transcript_id', 'target', $entry->target)} = 1; foreach my $other_source (@{ $other_sources }) { $source_genes{$self->cache->get_by_key('genes_by_transcript_id', 'source', $other_source)} = 1; } foreach my $other_target (@{ $other_targets }) { $target_genes{$self->cache->get_by_key('genes_by_transcript_id', 'target', $other_target)} = 1; } # only add mapping if only one source and target gene involved if (scalar(keys %source_genes) == 1 and scalar(keys %target_genes) == 1) { #$self->logger->debug('O'); $mappings->add_Entry($entry); } } else { #$self->logger->debug('A'); # this is the best mapping, add it $mappings->add_Entry($entry); } $sources_done->{$entry->source} = 1; $targets_done->{$entry->target} = 1; } # create checkpoint $mappings->write_to_file; return $mappings; } 1;
muffato/ensembl
modules/Bio/EnsEMBL/IdMapping/InternalIdMapper/EnsemblTranscriptGeneric.pm
Perl
apache-2.0
8,532
#!/usr/bin/perl package RVM v1.0.0; use v5.14; # Pragmas use strict; use warnings; # Função que avalia se um escalar e um número, ou não. use Scalar::Util qw(looks_like_number); # Pacote com implementações das funções de assembly. use functions; sub ctrl { ## VARIÁVEIS ###################################################### my $obj = shift; # Carrega objeto my $i = \$obj->{'PC'}; # Alias para o registrador my $lbl = $obj->{'LABEL'}; # Alias para os lABELs my $prog = $obj->{'PROG'}; # Alias para o vetor de programas my $f = 0; # Escalar para o nome do comando my $arg = 0; # Escalar para o argumento do comando my $stack = 0; # Controle da pilha ## CARREGA LABELS ################################################# $$i = 0; # Zera contador de linhas for my $code (@$prog) { # Carrega labels e transforma linhas # só de labels em linhas com a string "0" $code->[0] = "0" unless defined($code->[0]); $$lbl{$code->[2]} = $$i if defined($code->[2]); $$i++; } ## EXECUTA CÓDIGOS ################################################ $f = $$prog[0][0]; # Carrega primeiro comando $$i = 0; while($f ne 'END') # Incrementa PC { $arg = $$prog[$$i][1]; # Carrega argumento my $line = $$i+1; $$i++; # Incrementa PC if($f ne "0") { $stack = $obj->$f($arg, $stack); } # Chama função # Tratamento de erros com o retorno da função given($stack) { when(-1) { die "Falha de segmentação, chefe! Linha $line\n"; } when(-2) { die "Operacao invalida, chefe! Linha $line\n"; } when(-3) { die "Não há label com este nome, chefe! Linha $line\n"; } default { $f = $$prog[$$i][0]; } # Carrega próximo comando } } # while } return 1;
renatocf/MAC0242-PROJECT
lib/RVM/ctrl.pm
Perl
apache-2.0
2,098
package API::Asn; # # Copyright 2015 Comcast Cable Communications Management, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # # JvD Note: you always want to put Utils as the first use. Sh*t don't work if it's after the Mojo lines. use UI::Utils; use Mojo::Base 'Mojolicious::Controller'; use Data::Dumper; # Index sub index { my $self = shift; my @data; my $orderby = $self->param('orderby') || "asn"; my $rs_data = $self->db->resultset("Asn")->search( undef, { prefetch => [ { 'cachegroup' => undef } ], order_by => "me." . $orderby } ); while ( my $row = $rs_data->next ) { push( @data, { "id" => $row->id, "asn" => $row->asn, "cachegroup" => $row->cachegroup->name, "lastUpdated" => $row->last_updated, } ); } $self->success( \@data ); } # Show sub show { my $self = shift; my $id = $self->param('id'); my $rs_data = $self->db->resultset("Asn")->search( { 'me.id' => $id }, { prefetch => [ 'cachegroup' ] } ); my @data = (); while ( my $row = $rs_data->next ) { push( @data, { "id" => $row->id, "asn" => $row->asn, "lastUpdated" => $row->last_updated, "cachegroup" => { "id" => $row->cachegroup->id, "name" => $row->cachegroup->name } } ); } $self->success( \@data ); } # Index sub v11_index { my $self = shift; my @data; my $orderby = $self->param('orderby') || "asn"; my $rs_data = $self->db->resultset("Asn")->search( undef, { prefetch => [ { 'cachegroup' => undef } ], order_by => "me." . $orderby } ); while ( my $row = $rs_data->next ) { push( @data, { "id" => $row->id, "asn" => $row->asn, "cachegroup" => $row->cachegroup->name, "lastUpdated" => $row->last_updated, } ); } $self->success( { "asns" => \@data } ); } 1;
mtorluemke/traffic_control
traffic_ops/app/lib/API/Asn.pm
Perl
apache-2.0
2,312
#!/usr/bin/env perl use strict; my $family_type = shift @ARGV; my $dir = $ENV{'EST_PRECOMPUTE_SCRIPTS'}; die "Input pfam/gene3d/ssf unless " unless defined $family_type; die "Load EST Module\n" unless defined $dir; my @bins = split "\n", `ls $dir/lists/$family_type/blast/ | sort -n`; my @todo; my @results; my %hash; foreach my $bin(@bins){ #print "About to check $bin\n"; chomp $bin; my $todo = "$dir/lists/pfam/blast/$bin"; my $results = "$dir/qsub/$family_type/blast/blast_check/$bin"; # print `wc -l $todo | cut -f1 -d' ' `; # print `wc -l $results | cut -f1 -d ' '`; $hash{$bin}{'todo'} = `wc -l $todo | cut -f1 -d' '`; $hash{$bin}{'missing'}= `wc -l $results | cut -f1 -d' '` - 1; } foreach my $bin(@bins){ chomp $bin; chomp(my $todo = $hash{$bin}{'todo'}); chomp(my $results = $hash{$bin}{'missing'}); my $complete = ""; my $candidate = ""; if($results ==0 ){ $complete = " complete "; } my $twenty_percent = .20 * $todo; if($results < $twenty_percent && $results != 0){ $candidate = " candidate[lowernodes] "; } my $message = "$bin todo[$todo] missing[$results] $complete $candidate\n"; print $message; }
EnzymeFunctionInitiative/est-precompute-bw
4-blast_check.pl
Perl
apache-2.0
1,145
# # Copyright 2022 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package network::ruggedcom::mode::components::psu; use strict; use warnings; my %map_states_psu = ( 1 => 'notPresent', 2 => 'functional', 3 => 'notFunctional', 4 => 'notConnected', ); my $oid_rcDeviceStsPowerSupply1_entry = '.1.3.6.1.4.1.15004.4.2.2.4'; my $oid_rcDeviceStsPowerSupply1 = '.1.3.6.1.4.1.15004.4.2.2.4.0'; my $oid_rcDeviceStsPowerSupply2_entry = '.1.3.6.1.4.1.15004.4.2.2.5'; my $oid_rcDeviceStsPowerSupply2 = '.1.3.6.1.4.1.15004.4.2.2.5.0'; sub load { my ($self) = @_; push @{$self->{request}}, { oid => $oid_rcDeviceStsPowerSupply1_entry }, { oid => $oid_rcDeviceStsPowerSupply2_entry }; } sub check { my ($self) = @_; $self->{output}->output_add(long_msg => "Checking power supplies"); $self->{components}->{psu} = {name => 'psus', total => 0, skip => 0}; return if ($self->check_filter(section => 'psu')); my $instance = 0; foreach my $value (($self->{results}->{$oid_rcDeviceStsPowerSupply1}, $self->{results}->{$oid_rcDeviceStsPowerSupply2})) { $instance++; next if (!defined($value)); my $psu_state = $value; next if ($self->check_filter(section => 'psu', instance => $instance)); next if ($map_states_psu{$psu_state} eq 'notPresent' && $self->absent_problem(section => 'psu', instance => $instance)); $self->{components}->{psu}->{total}++; $self->{output}->output_add(long_msg => sprintf("Power Supply '%s' state is %s.", $instance, $map_states_psu{$psu_state})); my $exit = $self->get_severity(section => 'psu', value => $map_states_psu{$psu_state}); if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) { $self->{output}->output_add(severity => $exit, short_msg => sprintf("Power Supply '%s' state is %s.", $instance, $map_states_psu{$psu_state})); } } } 1;
centreon/centreon-plugins
network/ruggedcom/mode/components/psu.pm
Perl
apache-2.0
2,732
############################################################ # # $Id$ # Sys::Filesystem - Retrieve list of filesystems and their properties # # Copyright 2004,2005,2006 Nicola Worthington # Copyright 2009 Jens Rehsack # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ############################################################ package Sys::Filesystem::Unix; # vim:ts=4:sw=4:tw=78 use 5.008001; use strict; use warnings; use vars qw($VERSION); use Carp qw(croak); use Cwd 'abs_path'; use Fcntl qw(:flock); use IO::File; $VERSION = '1.406'; sub version() { return $VERSION; } # Default fstab and mtab layout my @keys = qw(fs_spec fs_file fs_vfstype fs_mntops fs_freq fs_passno); my %special_fs = ( swap => 1, proc => 1 ); sub new { ref( my $class = shift ) && croak 'Class name required'; my %args = @_; my $self = bless( {}, $class ); $args{canondev} and $self->{canondev} = 1; # Defaults $args{fstab} ||= '/etc/fstab'; $args{mtab} ||= '/etc/mtab'; $self->readFsTab( $args{fstab}, \@keys, [ 0, 1, 2 ], \%special_fs ); $self->readMntTab( $args{mtab}, \@keys, [ 0, 1, 2 ], \%special_fs ); delete $self->{canondev}; $self; } sub readFsTab($\@\@\%) { my ( $self, $fstabPath, $fstabKeys, $pridx, $special_fs ) = @_; # Read the fstab local $/ = "\n"; if ( my $fstab = IO::File->new( $fstabPath, 'r' ) ) { while (<$fstab>) { next if ( /^\s*#/ || /^\s*$/ ); # $_ =~ s/#.*$//; # next if( /^\s*$/ ); my @vals = split( ' ', $_ ); $self->{canondev} and -l $vals[ $pridx->[0] ] and $vals[ $pridx->[0] ] = abs_path( $vals[ $pridx->[0] ] ); $self->{ $vals[ $pridx->[1] ] }->{mount_point} = $vals[ $pridx->[1] ]; $self->{ $vals[ $pridx->[1] ] }->{device} = $vals[ $pridx->[0] ]; $self->{ $vals[ $pridx->[1] ] }->{unmounted} = 1 unless ( defined( $self->{ $vals[ $pridx->[1] ] }->{mounted} ) ); if ( defined( $pridx->[2] ) ) { my $vfs_type = $self->{ $vals[ $pridx->[1] ] }->{fs_vfstype} = $vals[ $pridx->[2] ]; $self->{ $vals[ $pridx->[1] ] }->{special} = 1 if ( defined( $special_fs->{$vfs_type} ) ); } else { $self->{ $vals[ $pridx->[1] ] }->{special} = 0 unless ( defined( $self->{ $vals[ $pridx->[1] ] }->{special} ) ); } for ( my $i = 0; $i < @{$fstabKeys}; ++$i ) { $self->{ $vals[ $pridx->[1] ] }->{ $fstabKeys->[$i] } = defined( $vals[$i] ) ? $vals[$i] : ''; } } $fstab->close(); 1; } else { 0; } } sub readMntTab($\@\@\%) { my ( $self, $mnttabPath, $mnttabKeys, $pridx, $special_fs ) = @_; # Read the mtab local $/ = "\n"; my $mtab; if ( ( $mtab = IO::File->new( $mnttabPath, 'r' ) ) && flock( $mtab, LOCK_SH | LOCK_NB ) ) { while (<$mtab>) { next if ( /^\s*#/ || /^\s*$/ ); # $_ =~ s/#.*$//; # next if( /^\s*$/ ); my @vals = split( /\s+/, $_ ); $self->{canondev} and -l $vals[ $pridx->[0] ] and $vals[ $pridx->[0] ] = abs_path( $vals[ $pridx->[0] ] ); delete $self->{ $vals[ $pridx->[1] ] }->{unmounted} if ( exists( $self->{ $vals[ $pridx->[1] ] }->{unmounted} ) ); $self->{ $vals[ $pridx->[1] ] }->{mounted} = 1; $self->{ $vals[ $pridx->[1] ] }->{mount_point} = $vals[ $pridx->[1] ]; $self->{ $vals[ $pridx->[1] ] }->{device} = $vals[ $pridx->[0] ]; if ( defined( $pridx->[2] ) ) { my $vfs_type = $self->{ $vals[ $pridx->[1] ] }->{fs_vfstype} = $vals[ $pridx->[2] ]; $self->{ $vals[ $pridx->[1] ] }->{special} = 1 if ( defined( $special_fs->{$vfs_type} ) ); } else { $self->{ $vals[ $pridx->[1] ] }->{special} = 0 unless ( defined( $self->{ $vals[ $pridx->[1] ] }->{special} ) ); } for ( my $i = 0; $i < @{$mnttabKeys}; ++$i ) { $self->{ $vals[ $pridx->[1] ] }->{ $mnttabKeys->[$i] } = defined( $vals[$i] ) ? $vals[$i] : ''; } } $mtab->close(); 1; } else { 0; } } sub readMounts { my ( $self, $mount_rx, $pridx, $keys, $special, @lines ) = @_; foreach my $line (@lines) { if ( my @vals = $line =~ $mount_rx ) { $self->{canondev} and -l $vals[ $pridx->[0] ] and $vals[ $pridx->[0] ] = abs_path( $vals[ $pridx->[0] ] ); $self->{ $vals[ $pridx->[1] ] }->{mount_point} = $vals[ $pridx->[1] ]; $self->{ $vals[ $pridx->[1] ] }->{device} = $vals[ $pridx->[0] ]; $self->{ $vals[ $pridx->[1] ] }->{mounted} = 1; delete $self->{ $vals[ $pridx->[1] ] }->{unmounted} if ( exists( $self->{ $vals[ $pridx->[1] ] }->{unmounted} ) ); if ( defined( $pridx->[2] ) ) { my $vfs_type = $self->{ $vals[ $pridx->[1] ] }->{fs_vfstype} = $vals[ $pridx->[2] ]; $self->{ $vals[ $pridx->[1] ] }->{special} = 1 if ( defined( $special->{$vfs_type} ) ); } elsif ( !defined( $self->{ $vals[ $pridx->[1] ] }->{special} ) ) { $self->{ $vals[ $pridx->[1] ] }->{special} = 0; } for ( my $i = 0; $i < @{$keys}; ++$i ) { $self->{ $vals[ $pridx->[1] ] }->{ $keys->[$i] } = defined( $vals[$i] ) ? $vals[$i] : ''; } } } $self; } sub readSwap { my ( $self, $swap_rx, @lines ) = @_; foreach my $line (@lines) { if ( my ($dev) = $line =~ $swap_rx ) { $self->{canondev} and -l $dev and $dev = abs_path($dev); $self->{none}->{mount_point} ||= 'none'; $self->{none}->{device} = $dev; $self->{none}->{fs_vfstype} = 'swap'; $self->{none}->{mounted} = 1; $self->{none}->{special} = 1; delete $self->{none}->{unmounted}; } } $self; } 1; =pod =head1 NAME Sys::Filesystem::Unix - Return generic Unix filesystem information to Sys::Filesystem =head1 SYNOPSIS See L<Sys::Filesystem>. =head1 INHERITANCE Sys::Filesystem::Unix ISA UNIVERSAL =head1 METHODS =over 4 =item version() Return the version of the (sub)module. =item readFsTab This method provides the capability to parse a standard unix fstab file. It expects following arguments: =over 8 =item fstabPath Full qualified path to the fstab file to read. =item fstabKeys The column names for the fstab file through an array reference. =item special_fs Hash reference containing the names of all special file systems having a true value as key. =back This method return true in case the specified file could be opened for reading, false otherwise. =item readMntTab This method provides the capability to read abd parse a standard unix mount-tab file. The file is locked using flock after opening it. It expects following arguments: =over 8 =item mnttabPath Full qualified path to the mnttab file to read. =item mnttabKeys The column names for the mnttab file through an array reference. =item $special_fs Hash reference containing the names of all special file systems having a true value as key. =back This method return true in case the specified file could be opened for reading and locked, false otherwise. =item readMounts This method is called to parse the information got from C<mount> system command. It expects following arguments: =over 8 =item mount_rx Regular expression to extract the information from each mount line. =item pridx Array reference containing the index for primary keys of interest in match in following order: device, mount_point, type. =item keys Array reference of the columns of the match - in order of paranteses in regular expression. =item special Array reference containing the names of the special file system types. =item lines Array containing the lines to parse. =back =item readSwap This method is called to parse the information from the swap status. It expects following arguments: =over 8 =item swap_rx Regular expression to extract the information from each swap status line. This regular expression should have exact one pair of parantheses to identify the swap device. =item lines Array containing the lines to parse. =back =back =head1 VERSION $Id$ =head1 AUTHOR Nicola Worthington <nicolaw@cpan.org> - L<http://perlgirl.org.uk> Jens Rehsack <rehsack@cpan.org> - L<http://www.rehsack.de/> =head1 COPYRIGHT Copyright 2004,2005,2006 Nicola Worthington. Copyright 2008-2014 Jens Rehsack. This software is licensed under The Apache Software License, Version 2.0. L<http://www.apache.org/licenses/LICENSE-2.0> =cut
gitpan/Sys-Filesystem
lib/Sys/Filesystem/Unix.pm
Perl
apache-2.0
9,700
#!/usr/bin/perl # Mingyu @ May 9 2013 # Summarize the results of 5_1_batch.pl use strict; use File::Path qw(make_path); use Math::NumberCruncher; #my @dTypes = ("NPNV", "NANWNO", "NPNVNONANW", "NP2DNV2D", "NP2DNV2DNONANW"); my @dTypes = ("NPNV"); unless (-d "results") { make_path "results"; } foreach my $voc ("1k", "1kf", "100k") { foreach my $nbest (1, 2, 3, 5) { open LOG, ">results/results_ext_bigram_$voc\_$nbest"."best.txt" or die $!; foreach my $dtype (@dTypes) { my @word_err_cnt = ([],[]); my @word_err_rate = ([],[]); my @char_err_rate = ([],[]); foreach my $t (0..1) { my $path = "products/$dtype/M1/tree$t"; open LOG_TREE, "$path/log_dec_ext_bigram_$voc\_nbest.log" or die "$dtype tree$t $voc"; OUTER:while( my $line = <LOG_TREE> ) { if ($line =~ /^HResults -A -d $nbest/) { while ($line = <LOG_TREE>) { if ($line =~ /^SENT:/){ if ($line =~ /H=([\d]+), S=([\d]+), N=([\d]+)/){ push @{$word_err_cnt[$t]}, $2; push @{$word_err_rate[$t]}, $2/$3*100; } } elsif ($line =~ /^WORD:/){ if ($line =~ /H=([\d]+), D=([\d]+), S=([\d]+), I=([\d]+), N=([\d]+)/){ push @{$char_err_rate[$t]}, ($2+$3+$4)/$5*100; last OUTER; } } } } } close LOG_TREE; } print LOG "[$dtype]\n"; print LOG "\ttree0\ttree1\n"; my $str = sprintf("%s\t%3.2f\t%3.2f\n", "M1", $word_err_cnt[0][0], $word_err_cnt[1][0]); print LOG $str; print LOG "(WER \%)\n"; print LOG sprintf("avg:\t%5.2f\t%5.2f\n", $word_err_rate[0][0], $word_err_rate[1][0]); print LOG "(CER \%)\n"; print LOG sprintf("avg:\t%5.2f\t%5.2f\n", $char_err_rate[0][0], $char_err_rate[1][0]); print LOG "\n\n"; } close LOG; } }
mingyu623/6DMG
6DMG_htk/words_letter_based/5_2_stats_ext_bigram_nbest.pl
Perl
bsd-2-clause
1,814
package Twitter::Authentication; =head1 NAME Twitter::Authentication - Basic functions for Twitter authentication. =head1 SYNOPSIS use Twitter::Authentication; my $credentials = Twitter::Authentication::credentials(); my $login_data = Twitter::Authentication::login_struct(); my $parsed_xml = Twitter::Authentication::read_config(); =head1 DESCRIPTION =over 4 =cut use Twitter::Credentials; use XML::Simple; use Cwd; =item credentials() Returns a Credentials object properly filled with 'username' and 'password' Parameters: none Returns: Success: A Credentials instance Failure: Returns null context / undef for all scalar purposes =cut sub credentials { my ($args) = @_; my $ls_args = { filename => $args->{filename} }; my $struct = login_struct($ls_args); return new Twitter::Credentials($struct); } =item login_struct() Returns a hashref with 'username' and 'password' filled in by read_config() Parameters: none Returns: Success: A hashref with username/password keys filled in Failure: Returns null context / undef for all purposes =cut sub login_struct { my ($args) = @_; my ($username, $password); my $rc_args = { filename => $args->{filename} }; my $xml = read_config($rc_args); if ( !defined($xml) ) { return; } my $struct = { username => $xml->{username}, password => $xml->{password} }; return $struct; } =item read_config([$filename]) Reads ./credentials.xml and returns a DOM-like XML hashref containing keys 'username' and 'password' Parameters: $args hashref may contain an optional path to credentials.xml in the 'filename' key [Defaults to /etc/twitter/credentials.xml] Returns: Success: A XML tree hashref with the root element removed Failure: Returns null context / undef for all purposes =cut sub read_config { my ($args) = @_; my $xml; my $filename = $args->{filename}; my $orig_filename = $filename; my $cwd; if ( !(-e $filename) ) { $cwd = getcwd(); $filename = "$cwd/credentials.xml"; } if ( !(-e $filename) ) { $filename = "/etc/twitter/credentials.xml"; } if ( !(-e $filename) ) { # credentials.xml file not found die "Fatal: Unable to find the credentials.xml file under $orig_filename, $cwd/credentials.xml or /etc/twitter/credentials.xml (In that order)"; return; } eval { $xml = XMLin($filename); }; if ($@) { die "Fatal XML error parsing $filename: $@\n"; return; } return $xml; } =back =cut 1;
gitpan/Twitter
lib/Twitter/Authentication.pm
Perl
bsd-3-clause
2,720
#!/usr/bin/perl -w my $sleep_duration = 5; warn "starting...\n"; warn "sleeping $sleep_duration seconds...\n"; sleep $sleep_duration; my $a = $ARGV[0]; my $b = $ARGV[1]; warn "calculating $a/$b...\n"; my $c=$a/$b; print "$c\n"; warn "done!\n"; exit 0;
cparnot/GridStuffer
Demo/Demo5/demo5.pl
Perl
bsd-3-clause
259
#!/usr/bin/perl # # # $rdir = $ARGV[0]; $exe = $ARGV[1]; $bdir = $ENV{'BIN_ROOT_DIR'}; $cmd ="${rdir}/runinitmem ${bdir}/test/${exe}"; print <<EOF *** Tst: $__FILE__ Cmd: $cmd *** EOF ; system($cmd); $stat = $? >> 8; if ($stat != 0) { print "*** test failed ;-( ***\n"; exit(1); } print "*** test passed ;-) ***\n";
MoserMichael/cstuff
preloadut/initmem/test/initmemtest.pl
Perl
bsd-3-clause
336
:- module(m3,[ ]). :- use_module(m1). data(m3).
TeamSPoon/logicmoo_base
prolog/logicmoo/pdt_server/PDT Examples/transparent/m3.pl
Perl
mit
50
/* Part of XPCE --- The SWI-Prolog GUI toolkit Author: Jan Wielemaker and Anjo Anjewierden E-mail: jan@swi.psy.uva.nl WWW: http://www.swi.psy.uva.nl/projects/xpce/ Copyright (c) 1997-2011, University of Amsterdam All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ :- module(pce_help_messages, []). :- use_module(library(pce)). :- pce_global(@help_message_window, new(help_message_window)). :- pce_begin_class(help_message_window, dialog, "Window to display <-help_message"). class_variable(background, colour, when(@pce?window_system == windows, win_infobk, burlywood1), "Ballon background"). class_variable(foreground, colour, when(@pce?window_system == windows, win_infotext, black)). variable(handler, handler, get, "Handler for intercept"). variable(message, string*, get, "Currently displayed message"). initialise(W) :-> send(W, slot, handler, handler(mouse, message(W, try_hide, @event))), send_super(W, initialise), get(W, frame, Frame), send(Frame, kind, popup), send(Frame, sensitive, @off), send(Frame, border, 0), send(Frame?tile, border, 0), send(W, gap, size(5, 2)), ( get(@pce, window_system, windows) % Hack -> send(W, pen, 1) ; send(W, pen, 0) ), send(W, append, new(L, label(feedback, '', normal))), send(L, length, 0), send(Frame, create). owner(W, Owner:[any]*) :-> "Maintain hyperlink to the owner":: ( Owner == @nil -> send(W, delete_hypers, owner) ; Owner == @default -> true % no change ; new(_, help_hyper(Owner, W, help_baloon, owner)) ). owner(W, Owner:any) :<- get(W, hypered, owner, Owner). try_hide(W, Ev:event) :-> get(W, owner, Owner), ( send(Ev, inside, Owner), ( send(Ev, is_a, loc_move) ; send(Ev, is_a, loc_still) ) -> %send(@pce, format, '%O: Move/still event\n', Owner), get(W, message, OldMsg), ( get(Owner, help_message, tag, Ev, Msg) -> %send(@pce, format, '%O: yielding %s\n', Owner, Msg), ( OldMsg \== @nil, send(Msg, equal, OldMsg) -> ( send(Ev, is_a, loc_still) -> send(W, adjust_position, Ev) ; true ) ; send(W, feedback, Msg, Ev) ) ; ( get(W, message, @nil) -> true ; send(W, feedback, @nil, Ev) ) ) ; send(W, owner, @nil), send(W, hide), fail % normal event-processing ). hide(W) :-> "Remove from the display":: send(W, show, @off), get(W, handler, H), send(W?display?inspect_handlers, delete, H). feedback(W, S:string*, Ev:event, For:[any]*) :-> "Display window holding string and grab pointer":: send(W, owner, For), send(W, slot, message, S), ( S == @nil -> send(W, show, @off) ; get(W, member, feedback, L), send(L, selection, S), send(W, layout), send(W?frame, fit), send(W, adjust_position, Ev), send(W?display, inspect_handler, W?handler) ). adjust_position(W, Ev:event) :-> "Fix the position of the feedback window":: get(Ev, position, W?display, P), get(P, plus, point(5,5), point(FX, FY)), send(W?frame, set, FX, FY), send(W?frame, expose). :- pce_end_class. attribute_name(tag, help_tag). attribute_name(summary, help_summary). :- pce_extend_class(visual). help_message(Gr, What:{tag,summary}, Msg:string*) :-> "Associate a help message":: attribute_name(What, AttName), ( Msg == @nil -> send(Gr, delete_attribute, AttName) ; send(Gr, attribute, AttName, Msg) ). help_message(V, What:{tag,summary}, _Ev:[event], Msg:string) :<- attribute_name(What, AttName), get(V, attribute, AttName, Msg). :- pce_end_class. :- pce_extend_class(graphical). show_help_message(Gr, What:name, Ev:event) :-> find_help_message(Gr, What, Ev, Owner, Msg), send(@help_message_window, feedback, Msg, Ev, Owner). find_help_message(Gr, What, Ev, Gr, Msg) :- get(Gr, help_message, What, Ev, Msg), !. find_help_message(Gr, What, Ev, Owner, Msg) :- get(Gr, contained_in, Container), find_help_message(Container, What, Ev, Owner, Msg). :- pce_end_class. :- pce_extend_class(menu). help_message(Gr, What:{tag,summary}, Ev:[event], Msg:string) :<- "Fetch associated help message":: ( get(Gr, item_from_event, Ev, Item), get(Item, help_message, What, Msg) -> true ; get(Gr, get_super, help_message, What, Ev, Msg) ). :- pce_end_class. :- pce_begin_class(help_hyper, hyper, "Hyper between help-balloon and owner"). unlink_from(H) :-> "->hide the <-to part":: get(H, to, Part), ( object(Part) -> send(Part, hide) ; free(Part) ), free(H). :- pce_end_class. /******************************* * REGISTER * *******************************/ register_help_message_window :- send(@display, inspect_handler, handler(loc_still, message(@receiver, show_help_message, tag, @event))), send(@display, inspect_handler, handler(help, message(@receiver, show_help_message, summary, @event))). :- initialization register_help_message_window.
TeamSPoon/logicmoo_workspace
docker/rootfs/usr/local/lib/swipl/xpce/prolog/lib/help_message.pl
Perl
mit
6,938
########################################################################### # # This file is partially auto-generated by the DateTime::Locale generator # tools (v0.10). This code generator comes with the DateTime::Locale # distribution in the tools/ directory, and is called generate-modules. # # This file was generated from the CLDR JSON locale data. See the LICENSE.cldr # file included in this distribution for license details. # # Do not edit this file directly unless you are sure the part you are editing # is not created by the generator. # ########################################################################### =pod =encoding UTF-8 =head1 NAME DateTime::Locale::is_IS - Locale data examples for the is-IS locale. =head1 DESCRIPTION This pod file contains examples of the locale data available for the Icelandic Iceland locale. =head2 Days =head3 Wide (format) mánudagur þriðjudagur miðvikudagur fimmtudagur föstudagur laugardagur sunnudagur =head3 Abbreviated (format) mán. þri. mið. fim. fös. lau. sun. =head3 Narrow (format) M Þ M F F L S =head3 Wide (stand-alone) mánudagur þriðjudagur miðvikudagur fimmtudagur föstudagur laugardagur sunnudagur =head3 Abbreviated (stand-alone) mán. þri. mið. fim. fös. lau. sun. =head3 Narrow (stand-alone) M Þ M F F L S =head2 Months =head3 Wide (format) janúar febrúar mars apríl maí júní júlí ágúst september október nóvember desember =head3 Abbreviated (format) jan. feb. mar. apr. maí jún. júl. ágú. sep. okt. nóv. des. =head3 Narrow (format) J F M A M J J Á S O N D =head3 Wide (stand-alone) janúar febrúar mars apríl maí júní júlí ágúst september október nóvember desember =head3 Abbreviated (stand-alone) jan. feb. mar. apr. maí jún. júl. ágú. sep. okt. nóv. des. =head3 Narrow (stand-alone) J F M A M J J Á S O N D =head2 Quarters =head3 Wide (format) 1. fjórðungur 2. fjórðungur 3. fjórðungur 4. fjórðungur =head3 Abbreviated (format) F1 F2 F3 F4 =head3 Narrow (format) 1 2 3 4 =head3 Wide (stand-alone) 1. fjórðungur 2. fjórðungur 3. fjórðungur 4. fjórðungur =head3 Abbreviated (stand-alone) F1 F2 F3 F4 =head3 Narrow (stand-alone) 1 2 3 4 =head2 Eras =head3 Wide (format) fyrir Krist eftir Krist =head3 Abbreviated (format) f.Kr. e.Kr. =head3 Narrow (format) f.k. e.k. =head2 Date Formats =head3 Full 2008-02-05T18:30:30 = þriðjudagur, 5. febrúar 2008 1995-12-22T09:05:02 = föstudagur, 22. desember 1995 -0010-09-15T04:44:23 = laugardagur, 15. september -10 =head3 Long 2008-02-05T18:30:30 = 5. febrúar 2008 1995-12-22T09:05:02 = 22. desember 1995 -0010-09-15T04:44:23 = 15. september -10 =head3 Medium 2008-02-05T18:30:30 = 5. feb. 2008 1995-12-22T09:05:02 = 22. des. 1995 -0010-09-15T04:44:23 = 15. sep. -10 =head3 Short 2008-02-05T18:30:30 = 5.2.2008 1995-12-22T09:05:02 = 22.12.1995 -0010-09-15T04:44:23 = 15.9.-10 =head2 Time Formats =head3 Full 2008-02-05T18:30:30 = 18:30:30 UTC 1995-12-22T09:05:02 = 09:05:02 UTC -0010-09-15T04:44:23 = 04:44:23 UTC =head3 Long 2008-02-05T18:30:30 = 18:30:30 UTC 1995-12-22T09:05:02 = 09:05:02 UTC -0010-09-15T04:44:23 = 04:44:23 UTC =head3 Medium 2008-02-05T18:30:30 = 18:30:30 1995-12-22T09:05:02 = 09:05:02 -0010-09-15T04:44:23 = 04:44:23 =head3 Short 2008-02-05T18:30:30 = 18:30 1995-12-22T09:05:02 = 09:05 -0010-09-15T04:44:23 = 04:44 =head2 Datetime Formats =head3 Full 2008-02-05T18:30:30 = þriðjudagur, 5. febrúar 2008 kl. 18:30:30 UTC 1995-12-22T09:05:02 = föstudagur, 22. desember 1995 kl. 09:05:02 UTC -0010-09-15T04:44:23 = laugardagur, 15. september -10 kl. 04:44:23 UTC =head3 Long 2008-02-05T18:30:30 = 5. febrúar 2008 kl. 18:30:30 UTC 1995-12-22T09:05:02 = 22. desember 1995 kl. 09:05:02 UTC -0010-09-15T04:44:23 = 15. september -10 kl. 04:44:23 UTC =head3 Medium 2008-02-05T18:30:30 = 5. feb. 2008, 18:30:30 1995-12-22T09:05:02 = 22. des. 1995, 09:05:02 -0010-09-15T04:44:23 = 15. sep. -10, 04:44:23 =head3 Short 2008-02-05T18:30:30 = 5.2.2008, 18:30 1995-12-22T09:05:02 = 22.12.1995, 09:05 -0010-09-15T04:44:23 = 15.9.-10, 04:44 =head2 Available Formats =head3 E (ccc) 2008-02-05T18:30:30 = þri. 1995-12-22T09:05:02 = fös. -0010-09-15T04:44:23 = lau. =head3 EHm (E, HH:mm) 2008-02-05T18:30:30 = þri., 18:30 1995-12-22T09:05:02 = fös., 09:05 -0010-09-15T04:44:23 = lau., 04:44 =head3 EHms (E, HH:mm:ss) 2008-02-05T18:30:30 = þri., 18:30:30 1995-12-22T09:05:02 = fös., 09:05:02 -0010-09-15T04:44:23 = lau., 04:44:23 =head3 Ed (E d.) 2008-02-05T18:30:30 = þri. 5. 1995-12-22T09:05:02 = fös. 22. -0010-09-15T04:44:23 = lau. 15. =head3 Ehm (E, h:mm a) 2008-02-05T18:30:30 = þri., 6:30 e.h. 1995-12-22T09:05:02 = fös., 9:05 f.h. -0010-09-15T04:44:23 = lau., 4:44 f.h. =head3 Ehms (E, h:mm:ss a) 2008-02-05T18:30:30 = þri., 6:30:30 e.h. 1995-12-22T09:05:02 = fös., 9:05:02 f.h. -0010-09-15T04:44:23 = lau., 4:44:23 f.h. =head3 Gy (y G) 2008-02-05T18:30:30 = 2008 e.Kr. 1995-12-22T09:05:02 = 1995 e.Kr. -0010-09-15T04:44:23 = -10 f.Kr. =head3 GyMMM (MMM y G) 2008-02-05T18:30:30 = feb. 2008 e.Kr. 1995-12-22T09:05:02 = des. 1995 e.Kr. -0010-09-15T04:44:23 = sep. -10 f.Kr. =head3 GyMMMEd (E, d. MMM y G) 2008-02-05T18:30:30 = þri., 5. feb. 2008 e.Kr. 1995-12-22T09:05:02 = fös., 22. des. 1995 e.Kr. -0010-09-15T04:44:23 = lau., 15. sep. -10 f.Kr. =head3 GyMMMd (d. MMM y G) 2008-02-05T18:30:30 = 5. feb. 2008 e.Kr. 1995-12-22T09:05:02 = 22. des. 1995 e.Kr. -0010-09-15T04:44:23 = 15. sep. -10 f.Kr. =head3 H (HH) 2008-02-05T18:30:30 = 18 1995-12-22T09:05:02 = 09 -0010-09-15T04:44:23 = 04 =head3 Hm (HH:mm) 2008-02-05T18:30:30 = 18:30 1995-12-22T09:05:02 = 09:05 -0010-09-15T04:44:23 = 04:44 =head3 Hms (HH:mm:ss) 2008-02-05T18:30:30 = 18:30:30 1995-12-22T09:05:02 = 09:05:02 -0010-09-15T04:44:23 = 04:44:23 =head3 Hmsv (HH:mm:ss v) 2008-02-05T18:30:30 = 18:30:30 UTC 1995-12-22T09:05:02 = 09:05:02 UTC -0010-09-15T04:44:23 = 04:44:23 UTC =head3 Hmv (HH:mm v) 2008-02-05T18:30:30 = 18:30 UTC 1995-12-22T09:05:02 = 09:05 UTC -0010-09-15T04:44:23 = 04:44 UTC =head3 M (L) 2008-02-05T18:30:30 = 2 1995-12-22T09:05:02 = 12 -0010-09-15T04:44:23 = 9 =head3 MEd (E, d.M.) 2008-02-05T18:30:30 = þri., 5.2. 1995-12-22T09:05:02 = fös., 22.12. -0010-09-15T04:44:23 = lau., 15.9. =head3 MMM (LLL) 2008-02-05T18:30:30 = feb. 1995-12-22T09:05:02 = des. -0010-09-15T04:44:23 = sep. =head3 MMMEd (E, d. MMM) 2008-02-05T18:30:30 = þri., 5. feb. 1995-12-22T09:05:02 = fös., 22. des. -0010-09-15T04:44:23 = lau., 15. sep. =head3 MMMMEd (E, d. MMMM) 2008-02-05T18:30:30 = þri., 5. febrúar 1995-12-22T09:05:02 = fös., 22. desember -0010-09-15T04:44:23 = lau., 15. september =head3 MMMMd (d. MMMM) 2008-02-05T18:30:30 = 5. febrúar 1995-12-22T09:05:02 = 22. desember -0010-09-15T04:44:23 = 15. september =head3 MMMd (d. MMM) 2008-02-05T18:30:30 = 5. feb. 1995-12-22T09:05:02 = 22. des. -0010-09-15T04:44:23 = 15. sep. =head3 Md (d.M.) 2008-02-05T18:30:30 = 5.2. 1995-12-22T09:05:02 = 22.12. -0010-09-15T04:44:23 = 15.9. =head3 d (d) 2008-02-05T18:30:30 = 5 1995-12-22T09:05:02 = 22 -0010-09-15T04:44:23 = 15 =head3 h (h a) 2008-02-05T18:30:30 = 6 e.h. 1995-12-22T09:05:02 = 9 f.h. -0010-09-15T04:44:23 = 4 f.h. =head3 hm (h:mm a) 2008-02-05T18:30:30 = 6:30 e.h. 1995-12-22T09:05:02 = 9:05 f.h. -0010-09-15T04:44:23 = 4:44 f.h. =head3 hms (h:mm:ss a) 2008-02-05T18:30:30 = 6:30:30 e.h. 1995-12-22T09:05:02 = 9:05:02 f.h. -0010-09-15T04:44:23 = 4:44:23 f.h. =head3 hmsv (h:mm:ss a v) 2008-02-05T18:30:30 = 6:30:30 e.h. UTC 1995-12-22T09:05:02 = 9:05:02 f.h. UTC -0010-09-15T04:44:23 = 4:44:23 f.h. UTC =head3 hmv (h:mm a v) 2008-02-05T18:30:30 = 6:30 e.h. UTC 1995-12-22T09:05:02 = 9:05 f.h. UTC -0010-09-15T04:44:23 = 4:44 f.h. UTC =head3 ms (mm:ss) 2008-02-05T18:30:30 = 30:30 1995-12-22T09:05:02 = 05:02 -0010-09-15T04:44:23 = 44:23 =head3 y (y) 2008-02-05T18:30:30 = 2008 1995-12-22T09:05:02 = 1995 -0010-09-15T04:44:23 = -10 =head3 yM (M. y) 2008-02-05T18:30:30 = 2. 2008 1995-12-22T09:05:02 = 12. 1995 -0010-09-15T04:44:23 = 9. -10 =head3 yMEd (E, d.M.y) 2008-02-05T18:30:30 = þri., 5.2.2008 1995-12-22T09:05:02 = fös., 22.12.1995 -0010-09-15T04:44:23 = lau., 15.9.-10 =head3 yMMM (MMM y) 2008-02-05T18:30:30 = feb. 2008 1995-12-22T09:05:02 = des. 1995 -0010-09-15T04:44:23 = sep. -10 =head3 yMMMEd (E, d. MMM y) 2008-02-05T18:30:30 = þri., 5. feb. 2008 1995-12-22T09:05:02 = fös., 22. des. 1995 -0010-09-15T04:44:23 = lau., 15. sep. -10 =head3 yMMMM (MMMM y) 2008-02-05T18:30:30 = febrúar 2008 1995-12-22T09:05:02 = desember 1995 -0010-09-15T04:44:23 = september -10 =head3 yMMMd (d. MMM y) 2008-02-05T18:30:30 = 5. feb. 2008 1995-12-22T09:05:02 = 22. des. 1995 -0010-09-15T04:44:23 = 15. sep. -10 =head3 yMd (d.M.y) 2008-02-05T18:30:30 = 5.2.2008 1995-12-22T09:05:02 = 22.12.1995 -0010-09-15T04:44:23 = 15.9.-10 =head3 yQQQ (QQQ y) 2008-02-05T18:30:30 = F1 2008 1995-12-22T09:05:02 = F4 1995 -0010-09-15T04:44:23 = F3 -10 =head3 yQQQQ (QQQQ y) 2008-02-05T18:30:30 = 1. fjórðungur 2008 1995-12-22T09:05:02 = 4. fjórðungur 1995 -0010-09-15T04:44:23 = 3. fjórðungur -10 =head2 Miscellaneous =head3 Prefers 24 hour time? Yes =head3 Local first day of the week 1 (mánudagur) =head1 SUPPORT See L<DateTime::Locale>. =cut
jkb78/extrajnm
local/lib/perl5/DateTime/Locale/is_IS.pod
Perl
mit
10,010
#!/usr/bin/perl -w $m_port = 0; # master port $s_port = 0; # slave port $compare_flag = 0; sub print_usage { print "Usage) perl ./run_all_repl_test.pl master_port slave_port [compare]\n"; } if ($#ARGV >= 1 && $#ARGV <= 2) { $m_port = $ARGV[0]; $s_port = $ARGV[1]; if ($#ARGV == 2) { if ($ARGV[2] eq 'compare') { $compare_flag = 1; } else { print_usage(); die; } } print "master_port = $m_port\n"; print "slave_port = $s_port\n"; print "compare_flag = $compare_flag\n"; } else { print_usage(); die; } use Cwd 'abs_path'; use File::Basename; $filename = abs_path($0); $dir_path = dirname($filename); print "filename = $filename\n"; print "dir_path = $dir_path\n"; $jar_path = "$dir_path/../../arcus-java-client/target"; $cls_path = "$jar_path/arcus-java-client-1.7.0.jar" . ":$jar_path/zookeeper-3.4.5.jar:$jar_path/log4j-1.2.16.jar" . ":$jar_path/slf4j-api-1.6.1.jar:$jar_path/slf4j-log4j12-1.6.1.jar"; $comp_dir = "$dir_path/../compare"; $comp_cmd = "java -classpath $cls_path:$comp_dir" . " compare -keydump $dir_path/keydump*" . " -server localhost:$m_port -server localhost:$s_port"; print "comp_cmd = $comp_cmd\n"; @script_list = ( "standard_mix" , "simple_getset" , "simple_set" , "tiny_btree" , "torture_arcus_integration" , "torture_btree" # , "torture_btree_bytebkey" # , "torture_btree_bytemaxbkeyrange" # , "torture_btree_decinc" # , "torture_btree_exptime" # , "torture_btree_ins_del" # , "torture_btree_maxbkeyrange" # , "torture_btree_replace" # , "torture_cas" # , "torture_list" # , "torture_list_ins_del" # , "torture_set" # , "torture_set_ins_del" # , "torture_simple_decinc" #, "torture_simple_sticky" ); foreach $script (@script_list) { # Flush all before each test $cmd = "./flushall.bash localhost $m_port"; print "DO_FLUSH_ALL. $cmd\n"; system($cmd); sleep 1; # Create a temporary config file to run the test open CONF, ">tmp-config.txt" or die $!; print CONF "zookeeper=127.0.0.1:2181\n" . "service_code=test\n" . "client=30\n" . "rate=0\n" . "request=0\n" . "time=180\n" . "keyset_size=10000000\n" . "valueset_min_size=100\n" . "valueset_max_size=4000\n" . "pool=1\n" . "pool_size=30\n" . "pool_use_random=false\n" . "key_prefix=tmptest:\n" . "client_exptime=120\n" . "client_profile=" . $script . "\n"; close CONF; $cmd = "java -Xmx2g -Xms2g -Dnet.spy.log.LoggerImpl=net.spy.memcached.compat.log.Log4JLogger" . " -classpath $cls_path:. acp -config tmp-config.txt"; printf "RUN COMMAND=%s\n", $cmd; local $SIG{TERM} = sub { print "TERM SIGNAL\n" }; $ret = system($cmd); printf "EXIT CODE=%d\n", $ret; # Run comparison tool if ($compare_flag) { $cmd = "rm -f $dir_path/keydump*"; print "$cmd\n"; system($cmd); $cmd = "./dumpkey.bash localhost $m_port"; print "$cmd\n"; system($cmd); $cmd = "./dumpkey.bash localhost $s_port"; print "$cmd\n"; system($cmd); system($comp_cmd); } } print "END RUN_MC_TESTSCRIPTS\n"; print "To see errors. Try grep -e \"RUN COMMAND\" -e \"DIFFRENT\" -e \"bad=\" -e \"not ok\"\n";
jam2in/arcus-misc
acp-java/run_some_repl_test_v2.pl
Perl
apache-2.0
3,214
package Google::Ads::AdWords::v201406::AuthenticationError::Reason; use strict; use warnings; sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201406'}; # derivation by restriction use base qw( SOAP::WSDL::XSD::Typelib::Builtin::string); 1; __END__ =pod =head1 NAME =head1 DESCRIPTION Perl data type class for the XML Schema defined simpleType AuthenticationError.Reason from the namespace https://adwords.google.com/api/adwords/cm/v201406. The single reason for the authentication failure. This clase is derived from SOAP::WSDL::XSD::Typelib::Builtin::string . SOAP::WSDL's schema implementation does not validate data, so you can use it exactly like it's base type. # Description of restrictions not implemented yet. =head1 METHODS =head2 new Constructor. =head2 get_value / set_value Getter and setter for the simpleType's value. =head1 OVERLOADING Depending on the simple type's base type, the following operations are overloaded Stringification Numerification Boolification Check L<SOAP::WSDL::XSD::Typelib::Builtin> for more information. =head1 AUTHOR Generated by SOAP::WSDL =cut
gitpan/GOOGLE-ADWORDS-PERL-CLIENT
lib/Google/Ads/AdWords/v201406/AuthenticationError/Reason.pm
Perl
apache-2.0
1,141
#!/usr/bin/perl -w use strict; use CoGeX; use CoGe::Accessory::Web; use Data::Dumper; use Getopt::Long; use File::Path; use vars qw($DEBUG $GO $conf_file $coge $gid $restricted $P $ftid $user $pwd); GetOptions ( "debug=s" => \$DEBUG, "go=s" => \$GO, "conf_file|cf=s" => \$conf_file, "gid=i"=>\$gid, #genome id "ftid=i"=>\$ftid, #feature type id "u=s"=>\$user, "p=s"=>\$pwd, ); $P = CoGe::Accessory::Web::get_defaults($conf_file); unless ($P && $P->{DBNAME}) {usage();} #my $TEMPDIR = $P->{TEMPDIR}."copy_genome"; #mkpath( $TEMPDIR, 1, 0777 ); my $DBNAME = $P->{DBNAME}; my $DBHOST = $P->{DBHOST}; my $DBPORT = $P->{DBPORT}; my $DBUSER = $P->{DBUSER}; my $DBPASS = $P->{DBPASS}; $DBUSER = $user if $user; $DBPASS = $pwd if $pwd; my $connstr = "dbi:mysql:dbname=".$DBNAME.";host=".$DBHOST.";port=".$DBPORT; $coge = CoGeX->dbconnect(db_connection_string=>$connstr, db_name=>$DBUSER, db_passwd=>$DBPASS ); #$coge->storage->debugobj(new DBIxProfiler()); #$coge->storage->debug(1); unless ($coge && $gid) { usage(); } my $genome = $coge->resultset('Genome')->find($gid); foreach my $feat ($genome->features({feature_type_id=>$ftid})) { $feat->delete if $GO; } sub usage { print qq{ Usage: $0 -cf <coge config file> -gid <genome id> -ftid <feature type id> -go 1 }; exit; }
LyonsLab/coge
scripts/old/delete_features.pl
Perl
bsd-2-clause
1,382
# # Copyright 2017 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package apps::apcupsd::local::mode::linevoltage; use base qw(centreon::plugins::mode); use strict; use warnings; use apps::apcupsd::local::mode::libgetdata; sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; $self->{version} = '1.0'; $options{options}->add_options(arguments => { "hostname:s" => { name => 'hostname' }, "remote" => { name => 'remote' }, "ssh-option:s@" => { name => 'ssh_option' }, "ssh-path:s" => { name => 'ssh_path' }, "ssh-command:s" => { name => 'ssh_command', default => 'ssh' }, "timeout:s" => { name => 'timeout', default => 30 }, "sudo" => { name => 'sudo' }, "command:s" => { name => 'command', default => 'apcaccess' }, "command-path:s" => { name => 'command_path', default => '/sbin/' }, "command-options:s" => { name => 'command_options', default => ' status ' }, "command-options2:s" => { name => 'command_options2', default => ' 2>&1' }, "apchost:s" => { name => 'apchost', default => 'localhost' }, "apcport:s" => { name => 'apcport', default => '3551' }, "searchpattern:s" => { name => 'searchpattern', default => 'LINEV' }, "warning:s" => { name => 'warning', default => '' }, "critical:s" => { name => 'critical', default => '' }, }); return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::init(%options); if (!defined($self->{option_results}->{apchost})) { $self->{output}->add_option_msg(short_msg => "Need to specify an APC Host."); $self->{output}->option_exit(); } if (!defined($self->{option_results}->{apcport})) { $self->{output}->add_option_msg(short_msg => "Need to specify an APC Port."); $self->{output}->option_exit(); } if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{option_results}->{warning} . "'."); $self->{output}->option_exit(); } if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{option_results}->{critical} . "'."); $self->{output}->option_exit(); } } sub run { my ($self, %options) = @_; my $result = apps::apcupsd::local::mode::libgetdata::getdata($self); my $exit = $self->{perfdata}->threshold_check(value => $result, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); $self->{output}->output_add(severity => $exit, short_msg => sprintf($self->{option_results}->{searchpattern} . ": %f", $result)); $self->{output}->perfdata_add(label => $self->{option_results}->{searchpattern}, value => $result, warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning'), critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical') ); $self->{output}->display(); $self->{output}->exit(); } 1; __END__ =head1 MODE Check apcupsd Status =over 8 =item B<--apchost> IP used by apcupsd =item B<--apcport> Port used by apcupsd =item B<--warning> Warning Threshold =item B<--critical> Critical Threshold =item B<--remote> If you dont wanna install the apcupsd client on your local system you can run it remotely with 'ssh'. =item B<--hostname> Hostname to query (need --remote). =item B<--ssh-option> Specify multiple options like the user (example: --ssh-option='-l=centreon-engine' --ssh-option='-p=52'). =back =cut
Shini31/centreon-plugins
apps/apcupsd/local/mode/linevoltage.pm
Perl
apache-2.0
5,310
# Call.pm # # Copyright (c) 1995-2011 Paul Marquess. All rights reserved. # # This program is free software; you can redistribute it and/or # modify it under the same terms as Perl itself. package Filter::Util::Call ; require 5.005 ; require DynaLoader; require Exporter; use Carp ; use strict; use warnings; use vars qw($VERSION @ISA @EXPORT) ; @ISA = qw(Exporter DynaLoader); @EXPORT = qw( filter_add filter_del filter_read filter_read_exact) ; $VERSION = "1.43" ; sub filter_read_exact($) { my ($size) = @_ ; my ($left) = $size ; my ($status) ; croak ("filter_read_exact: size parameter must be > 0") unless $size > 0 ; # try to read a block which is exactly $size bytes long while ($left and ($status = filter_read($left)) > 0) { $left = $size - length $_ ; } # EOF with pending data is a special case return 1 if $status == 0 and length $_ ; return $status ; } sub filter_add($) { my($obj) = @_ ; # Did we get a code reference? my $coderef = (ref $obj eq 'CODE') ; # If the parameter isn't already a reference, make it one. $obj = \$obj unless ref $obj ; $obj = bless ($obj, (caller)[0]) unless $coderef ; # finish off the installation of the filter in C. Filter::Util::Call::real_import($obj, (caller)[0], $coderef) ; } bootstrap Filter::Util::Call ; 1; __END__ =head1 NAME Filter::Util::Call - Perl Source Filter Utility Module =head1 SYNOPSIS use Filter::Util::Call ; =head1 DESCRIPTION This module provides you with the framework to write I<Source Filters> in Perl. An alternate interface to Filter::Util::Call is now available. See L<Filter::Simple> for more details. A I<Perl Source Filter> is implemented as a Perl module. The structure of the module can take one of two broadly similar formats. To distinguish between them, the first will be referred to as I<method filter> and the second as I<closure filter>. Here is a skeleton for the I<method filter>: package MyFilter ; use Filter::Util::Call ; sub import { my($type, @arguments) = @_ ; filter_add([]) ; } sub filter { my($self) = @_ ; my($status) ; $status = filter_read() ; $status ; } 1 ; and this is the equivalent skeleton for the I<closure filter>: package MyFilter ; use Filter::Util::Call ; sub import { my($type, @arguments) = @_ ; filter_add( sub { my($status) ; $status = filter_read() ; $status ; } ) } 1 ; To make use of either of the two filter modules above, place the line below in a Perl source file. use MyFilter; In fact, the skeleton modules shown above are fully functional I<Source Filters>, albeit fairly useless ones. All they does is filter the source stream without modifying it at all. As you can see both modules have a broadly similar structure. They both make use of the C<Filter::Util::Call> module and both have an C<import> method. The difference between them is that the I<method filter> requires a I<filter> method, whereas the I<closure filter> gets the equivalent of a I<filter> method with the anonymous sub passed to I<filter_add>. To make proper use of the I<closure filter> shown above you need to have a good understanding of the concept of a I<closure>. See L<perlref> for more details on the mechanics of I<closures>. =head2 B<use Filter::Util::Call> The following functions are exported by C<Filter::Util::Call>: filter_add() filter_read() filter_read_exact() filter_del() =head2 B<import()> The C<import> method is used to create an instance of the filter. It is called indirectly by Perl when it encounters the C<use MyFilter> line in a source file (See L<perlfunc/import> for more details on C<import>). It will always have at least one parameter automatically passed by Perl - this corresponds to the name of the package. In the example above it will be C<"MyFilter">. Apart from the first parameter, import can accept an optional list of parameters. These can be used to pass parameters to the filter. For example: use MyFilter qw(a b c) ; will result in the C<@_> array having the following values: @_ [0] => "MyFilter" @_ [1] => "a" @_ [2] => "b" @_ [3] => "c" Before terminating, the C<import> function must explicitly install the filter by calling C<filter_add>. B<filter_add()> The function, C<filter_add>, actually installs the filter. It takes one parameter which should be a reference. The kind of reference used will dictate which of the two filter types will be used. If a CODE reference is used then a I<closure filter> will be assumed. If a CODE reference is not used, a I<method filter> will be assumed. In a I<method filter>, the reference can be used to store context information. The reference will be I<blessed> into the package by C<filter_add>. See the filters at the end of this documents for examples of using context information using both I<method filters> and I<closure filters>. =head2 B<filter() and anonymous sub> Both the C<filter> method used with a I<method filter> and the anonymous sub used with a I<closure filter> is where the main processing for the filter is done. The big difference between the two types of filter is that the I<method filter> uses the object passed to the method to store any context data, whereas the I<closure filter> uses the lexical variables that are maintained by the closure. Note that the single parameter passed to the I<method filter>, C<$self>, is the same reference that was passed to C<filter_add> blessed into the filter's package. See the example filters later on for details of using C<$self>. Here is a list of the common features of the anonymous sub and the C<filter()> method. =over 5 =item B<$_> Although C<$_> doesn't actually appear explicitly in the sample filters above, it is implicitly used in a number of places. Firstly, when either C<filter> or the anonymous sub are called, a local copy of C<$_> will automatically be created. It will always contain the empty string at this point. Next, both C<filter_read> and C<filter_read_exact> will append any source data that is read to the end of C<$_>. Finally, when C<filter> or the anonymous sub are finished processing, they are expected to return the filtered source using C<$_>. This implicit use of C<$_> greatly simplifies the filter. =item B<$status> The status value that is returned by the user's C<filter> method or anonymous sub and the C<filter_read> and C<read_exact> functions take the same set of values, namely: < 0 Error = 0 EOF > 0 OK =item B<filter_read> and B<filter_read_exact> These functions are used by the filter to obtain either a line or block from the next filter in the chain or the actual source file if there aren't any other filters. The function C<filter_read> takes two forms: $status = filter_read() ; $status = filter_read($size) ; The first form is used to request a I<line>, the second requests a I<block>. In line mode, C<filter_read> will append the next source line to the end of the C<$_> scalar. In block mode, C<filter_read> will append a block of data which is <= C<$size> to the end of the C<$_> scalar. It is important to emphasise the that C<filter_read> will not necessarily read a block which is I<precisely> C<$size> bytes. If you need to be able to read a block which has an exact size, you can use the function C<filter_read_exact>. It works identically to C<filter_read> in block mode, except it will try to read a block which is exactly C<$size> bytes in length. The only circumstances when it will not return a block which is C<$size> bytes long is on EOF or error. It is I<very> important to check the value of C<$status> after I<every> call to C<filter_read> or C<filter_read_exact>. =item B<filter_del> The function, C<filter_del>, is used to disable the current filter. It does not affect the running of the filter. All it does is tell Perl not to call filter any more. See L<Example 4: Using filter_del> for details. =back =head1 EXAMPLES Here are a few examples which illustrate the key concepts - as such most of them are of little practical use. The C<examples> sub-directory has copies of all these filters implemented both as I<method filters> and as I<closure filters>. =head2 Example 1: A simple filter. Below is a I<method filter> which is hard-wired to replace all occurrences of the string C<"Joe"> to C<"Jim">. Not particularly Useful, but it is the first example and I wanted to keep it simple. package Joe2Jim ; use Filter::Util::Call ; sub import { my($type) = @_ ; filter_add(bless []) ; } sub filter { my($self) = @_ ; my($status) ; s/Joe/Jim/g if ($status = filter_read()) > 0 ; $status ; } 1 ; Here is an example of using the filter: use Joe2Jim ; print "Where is Joe?\n" ; And this is what the script above will print: Where is Jim? =head2 Example 2: Using the context The previous example was not particularly useful. To make it more general purpose we will make use of the context data and allow any arbitrary I<from> and I<to> strings to be used. This time we will use a I<closure filter>. To reflect its enhanced role, the filter is called C<Subst>. package Subst ; use Filter::Util::Call ; use Carp ; sub import { croak("usage: use Subst qw(from to)") unless @_ == 3 ; my ($self, $from, $to) = @_ ; filter_add( sub { my ($status) ; s/$from/$to/ if ($status = filter_read()) > 0 ; $status ; }) } 1 ; and is used like this: use Subst qw(Joe Jim) ; print "Where is Joe?\n" ; =head2 Example 3: Using the context within the filter Here is a filter which a variation of the C<Joe2Jim> filter. As well as substituting all occurrences of C<"Joe"> to C<"Jim"> it keeps a count of the number of substitutions made in the context object. Once EOF is detected (C<$status> is zero) the filter will insert an extra line into the source stream. When this extra line is executed it will print a count of the number of substitutions actually made. Note that C<$status> is set to C<1> in this case. package Count ; use Filter::Util::Call ; sub filter { my ($self) = @_ ; my ($status) ; if (($status = filter_read()) > 0 ) { s/Joe/Jim/g ; ++ $$self ; } elsif ($$self >= 0) { # EOF $_ = "print q[Made ${$self} substitutions\n]" ; $status = 1 ; $$self = -1 ; } $status ; } sub import { my ($self) = @_ ; my ($count) = 0 ; filter_add(\$count) ; } 1 ; Here is a script which uses it: use Count ; print "Hello Joe\n" ; print "Where is Joe\n" ; Outputs: Hello Jim Where is Jim Made 2 substitutions =head2 Example 4: Using filter_del Another variation on a theme. This time we will modify the C<Subst> filter to allow a starting and stopping pattern to be specified as well as the I<from> and I<to> patterns. If you know the I<vi> editor, it is the equivalent of this command: :/start/,/stop/s/from/to/ When used as a filter we want to invoke it like this: use NewSubst qw(start stop from to) ; Here is the module. package NewSubst ; use Filter::Util::Call ; use Carp ; sub import { my ($self, $start, $stop, $from, $to) = @_ ; my ($found) = 0 ; croak("usage: use Subst qw(start stop from to)") unless @_ == 5 ; filter_add( sub { my ($status) ; if (($status = filter_read()) > 0) { $found = 1 if $found == 0 and /$start/ ; if ($found) { s/$from/$to/ ; filter_del() if /$stop/ ; } } $status ; } ) } 1 ; =head1 Filter::Simple If you intend using the Filter::Call functionality, I would strongly recommend that you check out Damian Conway's excellent Filter::Simple module. Damian's module provides a much cleaner interface than Filter::Util::Call. Although it doesn't allow the fine control that Filter::Util::Call does, it should be adequate for the majority of applications. It's available at http://search.cpan.org/dist/Filter-Simple/ =head1 AUTHOR Paul Marquess =head1 DATE 26th January 1996 =cut
leighpauls/k2cro4
third_party/perl/perl/lib/Filter/Util/Call.pm
Perl
bsd-3-clause
12,800
#!/usr/bin/perl -w # Copyright (C) 2004 by Steve Litt # Licensed with the GNU General Public License, Version 2 # ABSOLUTELY NO WARRANTY, USE AT YOUR OWN RISK # See http://www.gnu.org/licenses/gpl.txt use strict; # prevent hard to find errors use Node; # Use Node.pm tool ##################################################################### # This exercise demonstrates the most elemental use of Node.pm. # It does nothing more than read README.otl into a Node tree, and # then print the tree. # # Here's the high level logic: # Set up a Callback object to house the callback routines # Instantiate and configure a Parser object to parse README.otl # Instantiate a Walker object to walk the resulting node tree # Link Callbacks::cbPrintNode() as the Walker's entry callback # ##################################################################### ############################################################## # You need an object to house callback routines. The object can # be named anything, but it should have facilities to count up # errors and warnings. Its new() method should always be something # like what you see below, and there should have getErrors() and # getWarnings() methods. # # The cbPrintNode() method is typical of a simple callback routine. # All callback routines have exactly three arguments, $self, # $checker and $level. $self refers to the object containing # the callback routine, $checker is the node that called this # callback routine, and $level is the level of that node in the # hierarchy. Armed with these pieces of information, you can # perform almost any operation on the current node ($checker). # # The callback routines are called by the Parser object during # parsing. A callback routine can be called upon first entry # into a node, or it can be called upon reentry into that node # after processing all that node's children. The latter is # an excellent way of outputting end tags at the proper time. ############################################################## package Callbacks; sub new() { my($type) = $_[0]; my($self) = {}; bless($self, $type); $self->{'errors'} = 0; $self->{'warnings'} = 0; return($self); } sub getErrors(){return $_[0]->{'errors'};} sub getWarnings(){return $_[0]->{'warnings'};} sub cbPrintNode() { my($self, $checker, $level) = @_; unless (defined($checker)) {return -999;} # don't process undef node print $level, " ::: "; # print the level print $checker->getValue(); # print the text of the node print "\n"; } package Main; sub main() { #### PARSE FROM FILE README.otl my $parser = OutlineParser->new(); # instantiate parser $parser->setCommentChar("#"); # ignore lines starting with # $parser->fromFile(); # get input from file my $topNode=$parser->parse("README.otl"); #==================================================================== # The preceding statement parses file README.otl into a node hierarchy # and assigns the top level node of that hierarchy to $topNode. When # you run the program you'll notice that the text in $topNode does # not appear in README.otl, but instead has value # "Inserted by OutlineParser". # # This is a feature, not a bug. In order to accommodate the typical # case of an outline having several top level items, and yet still # be able to represent the whole hierarchy as a single top node, # the OutlineParser object creates a new node with value # " Inserted by OutlineParser" # and places all the outline's top level items under that newly # created node. # # If the outline you're working on is guaranteed to have only # a single top level item, and if you want that to be the top # level node, you can simply do the following: # # $topNode=$topNode->getFirstChild(); #==================================================================== #### INSTANTIATE THE Callbacks OBJECT my $callbacks = Callbacks->new(); #### WALK THE NODE TREE, #### OUTPUTTING LEVEL AND TEXT my $walker = Walker->new ( $topNode, # start with this node [\&Callbacks::cbPrintNode, $callbacks] # do this on entry to each node ); $walker->walk(); } main();
jleivaizq/dotfiles
vim/vim.symlink/bundle/vimoutliner/vimoutliner/scripts/Node/example_parse.pl
Perl
mit
4,136
package DDG::Goodie::IsAwesome::rp4; # ABSTRACT: rp4's first Goodie use DDG::Goodie; use strict; zci answer_type => "is_awesome_rp4"; zci is_cached => 1; triggers start => "duckduckhack rp4"; handle remainder => sub { return if $_; return "rp4 is awesome and has successfully completed the DuckDuckHack Goodie tutorial!"; }; 1;
viluon/zeroclickinfo-goodies
lib/DDG/Goodie/IsAwesome/rp4.pm
Perl
apache-2.0
343
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!! # This file is machine-generated by mktables from the Unicode # database, Version 6.1.0. Any changes made here will be lost! # !!!!!!! INTERNAL PERL USE ONLY !!!!!!! # This file is for internal use by core Perl only. The format and even the # name or existence of this file are subject to change without notice. Don't # use it directly. return <<'END'; 1740 1753 END
Dokaponteam/ITF_Project
xampp/perl/lib/unicore/lib/Sc/Buhd.pl
Perl
mit
421
#!/usr/bin/perl use CGI qw/ :standard /; use File::Temp qw/ tempfile tempdir /; # my $spellercss = '/speller/spellerStyle.css'; # by FredCK my $spellercss = '../spellerStyle.css'; # by FredCK # my $wordWindowSrc = '/speller/wordWindow.js'; # by FredCK my $wordWindowSrc = '../wordWindow.js'; # by FredCK my @textinputs = param( 'textinputs[]' ); # array # my $aspell_cmd = 'aspell'; # by FredCK (for Linux) my $aspell_cmd = '"C:\Program Files\Aspell\bin\aspell.exe"'; # by FredCK (for Windows) my $lang = 'en_US'; # my $aspell_opts = "-a --lang=$lang --encoding=utf-8"; # by FredCK my $aspell_opts = "-a --lang=$lang --encoding=utf-8 -H --rem-sgml-check=alt"; # by FredCK my $input_separator = "A"; # set the 'wordtext' JavaScript variable to the submitted text. sub printTextVar { for( my $i = 0; $i <= $#textinputs; $i++ ) { print "textinputs[$i] = decodeURIComponent('" . escapeQuote( $textinputs[$i] ) . "')\n"; } } sub printTextIdxDecl { my $idx = shift; print "words[$idx] = [];\n"; print "suggs[$idx] = [];\n"; } sub printWordsElem { my( $textIdx, $wordIdx, $word ) = @_; print "words[$textIdx][$wordIdx] = '" . escapeQuote( $word ) . "';\n"; } sub printSuggsElem { my( $textIdx, $wordIdx, @suggs ) = @_; print "suggs[$textIdx][$wordIdx] = ["; for my $i ( 0..$#suggs ) { print "'" . escapeQuote( $suggs[$i] ) . "'"; if( $i < $#suggs ) { print ", "; } } print "];\n"; } sub printCheckerResults { my $textInputIdx = -1; my $wordIdx = 0; my $unhandledText; # create temp file my $dir = tempdir( CLEANUP => 1 ); my( $fh, $tmpfilename ) = tempfile( DIR => $dir ); # temp file was created properly? # open temp file, add the submitted text. for( my $i = 0; $i <= $#textinputs; $i++ ) { $text = url_decode( $textinputs[$i] ); @lines = split( /\n/, $text ); print $fh "\%\n"; # exit terse mode print $fh "^$input_separator\n"; print $fh "!\n"; # enter terse mode for my $line ( @lines ) { # use carat on each line to escape possible aspell commands print $fh "^$line\n"; } } # exec aspell command my $cmd = "$aspell_cmd $aspell_opts < $tmpfilename 2>&1"; open ASPELL, "$cmd |" or handleError( "Could not execute `$cmd`\\n$!" ) and return; # parse each line of aspell return for my $ret ( <ASPELL> ) { chomp( $ret ); # if '&', then not in dictionary but has suggestions # if '#', then not in dictionary and no suggestions # if '*', then it is a delimiter between text inputs if( $ret =~ /^\*/ ) { $textInputIdx++; printTextIdxDecl( $textInputIdx ); $wordIdx = 0; } elsif( $ret =~ /^(&|#)/ ) { my @tokens = split( " ", $ret, 5 ); printWordsElem( $textInputIdx, $wordIdx, $tokens[1] ); my @suggs = (); if( $tokens[4] ) { @suggs = split( ", ", $tokens[4] ); } printSuggsElem( $textInputIdx, $wordIdx, @suggs ); $wordIdx++; } else { $unhandledText .= $ret; } } close ASPELL or handleError( "Error executing `$cmd`\\n$unhandledText" ) and return; } sub escapeQuote { my $str = shift; $str =~ s/'/\\'/g; return $str; } sub handleError { my $err = shift; print "error = '" . escapeQuote( $err ) . "';\n"; } sub url_decode { local $_ = @_ ? shift : $_; defined or return; # change + signs to spaces tr/+/ /; # change hex escapes to the proper characters s/%([a-fA-F0-9]{2})/pack "H2", $1/eg; return $_; } # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Display HTML # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # print <<EOF; Content-type: text/html; charset=utf-8 <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <link rel="stylesheet" type="text/css" href="$spellercss"/> <script src="$wordWindowSrc"></script> <script type="text/javascript"> var suggs = new Array(); var words = new Array(); var textinputs = new Array(); var error; EOF printTextVar(); printCheckerResults(); print <<EOF; var wordWindowObj = new wordWindow(); wordWindowObj.originalSpellings = words; wordWindowObj.suggestions = suggs; wordWindowObj.textInputs = textinputs; function init_spell() { // check if any error occured during server-side processing if( error ) { alert( error ); } else { // call the init_spell() function in the parent frameset if (parent.frames.length) { parent.init_spell( wordWindowObj ); } else { error = "This page was loaded outside of a frameset. "; error += "It might not display properly"; alert( error ); } } } </script> </head> <body onLoad="init_spell();"> <script type="text/javascript"> wordWindowObj.writeBody(); </script> </body> </html> EOF
walterfan/pims4php
util/fckeditor/editor/dialog/fck_spellerpages/spellerpages/server-scripts/spellchecker.pl
Perl
apache-2.0
4,662
#!/usr/bin/perl # # Example from Etienne Lawlor at https://groups.google.com/forum/#!msg/yelp-developer-support/Bm4WQET5ios/_x2KiQqK9QMJ # use LWP::UserAgent; use Net::OAuth; $Net::OAuth::PROTOCOL_VERSION = Net::OAuth::PROTOCOL_VERSION_1_0; use HTTP::Request::Common; my $ua = LWP::UserAgent->new; sub consumer_key { 'insert consumer key here' } sub consumer_secret { 'insert consumer secret here' } sub access_token { 'insert access token here' } sub access_token_secret { 'insert access token secret here' } sub user_url { 'http://api.yelp.com/v2/search?term=food&location=San+Francisco' } my $request = Net::OAuth->request('protected resource')->new( consumer_key => consumer_key(), consumer_secret => consumer_secret(), token => access_token(), token_secret => access_token_secret(), request_url => user_url(), request_method => 'GET', signature_method => 'HMAC-SHA1', timestamp => time, nonce => nonce(), ); $request->sign; print $request->to_url."\n"; my $res = $ua->request(GET $request->to_url); print $res->as_string; if ($res->is_success) { print "Success\n"; } else { die "Something went wrong"; } sub nonce { my @a = ('A'..'Z', 'a'..'z', 0..9); my $nonce = ''; for(0..31) { $nonce .= $a[rand(scalar(@a))]; } $nonce; }
jsuns/yelp-api
v2/perl/search.pl
Perl
mit
1,363
#!/usr/bin/perl -w use warnings; use strict; package loadconf; use Cwd qw(realpath); use File::Basename; my $fullpath = dirname(realpath($0)); # my $config = "/mnt/d/sys/debian/bio/config"; # my $setup = "/mnt/d/sys/debian/bio/setup"; my $print = 1; my $config = "$fullpath/config"; &loadConf; ###################### #USAGE: ###################### # use loadconf; # my %pref = &loadconf::loadConf; # # use Cwd qw(realpath); # use File::Basename; # my $fullpath = dirname(realpath($0)); # # my $wwwfolder = $pref{"htmlPath"}; # http folder # my $width = $pref{"width"};; # graphic width in pixels # my $multithread = $pref{"multithreadGraphic"}; # enable multithread # my $renice = $pref{"reniceGraphic"}; # renice process (increase priority - needs SUDO) # my $minscore = $pref{"minscore"}; sub loadConf { my %pref; open (CONFIG,"<$config"); while (<CONFIG>) { chomp; # no newline s/#.*//; # no comments s/^\s+//; # no leading white s/\s+$//; # no trailing white next unless length; # anything left? if (/(\S+)\s+\=\s+(\S+)/) { $pref{$1} = $2; }; }; close CONFIG; if ($print) { foreach my $key (sort keys %pref) { print "$key => " . $pref{$key} . "\n"; } } return %pref; }; 1;
sauloal/perlscripts
bioMail/loadconf.pm
Perl
mit
1,435
package ivent::DB::Schema; use strict; use warnings; use utf8; use Teng::Schema::Declare; base_row_class 'ivent::DB::Row'; table { name 'events'; pk 'id'; columns qw(id name started_at ended_at url capacity accepted wating location description); }; table { name 'events_tags'; pk 'id'; columns qw(id event_id tag_id); }; table { name 'tags'; pk 'id'; columns qw(id name); }; 1;
mihyaeru21/ivent
lib/ivent/DB/Schema.pm
Perl
mit
420
package O2CMS::Obj::Template::Object; # Description: Template for displaying an object. One template may be used for several classes. use strict; use base 'O2CMS::Obj::Template'; use O2 qw($context); use O2::Util::List qw(upush contains); #------------------------------------------------------------------------------- sub addUsableClass { my ($obj, $usableClass) = @_; my @usableClasses = $obj->getUsableClasses(); upush @usableClasses, $usableClass; $obj->setUsableClasses(@usableClasses); } #------------------------------------------------------------------------------- # Returns true if template may be used for objects of a class # If the template is usable for a super class of the given class, it's also usable for the given class sub isUsableForClass { my ($obj, $className) = @_; my $objectIntrospect = $context->getSingleton('O2::Util::ObjectIntrospect'); $objectIntrospect->setClass($className); my @classNames = ( $className, $objectIntrospect->getInheritedClasses() ); my @usableClasses = $obj->getUsableClasses(); foreach my $_className (@classNames) { return 1 if contains @usableClasses, $_className; } return 0; } #------------------------------------------------------------------------------- 1;
haakonsk/O2-CMS
lib/O2CMS/Obj/Template/Object.pm
Perl
mit
1,250
#!/usr/bin/perl use strict; use warnings; my $source_server = $ARGV[0]; my $help = <<EHELP usage: sudo perl $0 source_server desc: this script will copy users from one Linux system to another. params: source_server: the address of the server to copy users from EHELP ; if(!defined($source_server)) { print "source server must be defined\n"; print $help; exit(1); } my $name = getgrent(); if($name ne "root") { print "you must run this script as root! exiting...\n"; exit(1); } print "copying user accounts and passwords from $source_server\n"; print "backing up user acccounts and passwords on this machine\n"; if(!-d "/tmp/backup") { mkdir("/tmp/backup") || die "could not create backup dir $!\n"; } `cp /etc/passwd /etc/shadow /etc/group /etc/gshadow /tmp/backup`; print "copying user account and passwords from $source_server\n"; `scp $source_server:/etc/passwd /tmp/passwd`; `scp $source_server:/etc/group /tmp/group`; `scp $source_server:/etc/shadow /tmp/shadow`; `scp $source_server:/etc/gshadow /tmp/gshadow`; `cp /tmp/passwd /etc/passwd`; `cp /tmp/group /etc/group`; `cp /tmp/shadow /etc/shadow`; `cp /tmp/gshadow /etc/gshadow`; print "cleaning up\n"; unlink("/tmp/passwd"); unlink("/tmp/group"); unlink("/tmp/shadow"); unlink("/tmp/gshadow"); print "done!\n"; exit(0); print "migrating /home\n"; `rsync -av --delete $source_server:/home/ /home/`; print "done!\n";
f0rk/scripts
migrate_all_users.pl
Perl
mit
1,412
package App::Docker::Client::Socket; =head1 NAME App::Docker::Client - Simple and plain Docker client! =head1 VERSION Version 0.010300 =cut our $VERSION = '0.010300'; use 5.16.0; use strict; use warnings; use AnyEvent; use AnyEvent::Socket 'tcp_connect'; use AnyEvent::HTTP; use LWP::UserAgent; use JSON; use LWP::Protocol::http::SocketUnixAlt; =head2 new Constructor =cut sub new { my $class = shift; my $self = {@_}; bless $self, $class; return $self; } =head1 SUBROUTINES/METHODS =head2 attach =cut sub attach { my ( $self, $path, $query, $input, $output ) = @_; my $cv = AnyEvent->condvar; my $callback = sub { my ( $fh, $headers ) = @_; $fh->on_error( sub { $cv->send } ); $fh->on_eof( sub { $cv->send } ); my $out_hndl = AnyEvent::Handle->new( fh => $output ); $fh->on_read( sub { my ($handle) = @_; $handle->unshift_read( sub { my ($h) = @_; my $length = length $h->{rbuf}; $out_hndl->push_write( $h->{rbuf} ); substr $h->{rbuf}, 0, $length, ''; } ); } ); my $in_hndl = AnyEvent::Handle->new( fh => $input ); $in_hndl->on_read( sub { my ($h) = @_; $h->push_read( line => sub { my ( $h2, $line, $eol ) = @_; $fh->push_write( $line . $eol ); } ); } ); $in_hndl->on_eof( sub { $cv->send } ); }; tcp_connect( "unix/", '/var/run/docker.sock', $callback ); return $cv; } 1; # End of App::Docker::Client __END__ =head1 SYNOPSIS Sample to inspect a conatainer, for mor posibilities see at the Docker API documentation L<https://docs.docker.com/engine/api/v1.25/> use App::Docker::Client; my $client = App::Docker::Client->new(); my $hash_ref = $client->get('/containers/<container_id>/json'); Create a new container: $client->post('/containers/create', {}, { Name => 'container_name', Tty => 1, OpenStdin => 1, Image => 'perl', }); For a remote authority engine use it like that: use App::Docker::Client; my %hash = ( authority => '0.0.0.0:5435' ); my $client = App::Docker::Client->new( %hash ); my $hash_ref = $client->get('/containers/<container_id>/json'); To follow logs *STDOUT->autoflush(1); my $cv = $client->attach( '/containers/<container_id>/attach', { stream => 1, logs => 1, stdin => 1, stderr => 1, stdout => 1, tail => 50 }, \*STDIN, \*STDOUT ); $cv->recv; =head1 AUTHOR Mario Zieschang, C<< <mziescha at cpan.org> >> =head1 BUGS Please report any bugs or feature requests to C<bug-app-docker-client at rt.cpan.org>, or through the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=App-Docker-Client>. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes. =head1 SUPPORT You can find documentation for this module with the perldoc command. perldoc App::Docker::Client You can also look for information at: =over 4 =item * RT: CPAN's request tracker (report bugs here) L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=App-Docker-Client> =item * AnnoCPAN: Annotated CPAN documentation L<http://annocpan.org/dist/App-Docker-Client> =item * CPAN Ratings L<http://cpanratings.perl.org/d/App-Docker-Client> =item * Search CPAN L<http://search.cpan.org/dist/App-Docker-Client/> =back =head1 SEE ALSO This package was partly inspired by L<Net::Docker> by Peter Stuifzand and L<WWW::Docker> by Shane Utt but everyone has his own client and is near similar. =head1 LICENSE AND COPYRIGHT Copyright 2017 Mario Zieschang. This program is free software; you can redistribute it and/or modify it under the terms of the the Artistic License (2.0). You may obtain a copy of the full license at: L<http://www.perlfoundation.org/artistic_license_2_0> Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license. If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license. This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder. This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed. Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
mziescha/App-Docker-Client
lib/App/Docker/Client/Socket.pm
Perl
mit
5,919
#!C:\strawberry\perl\bin\perl.exe # Match and capture word that ends with letter 'a' and the up to five next # characters; display contents of both captures; use named captures use 5.020; use warnings; while (<>) { # take one input line at a time chomp; if (/\b(?<name>\w*a)\b(?<nextchar>.{0,5})/) { print "Matched: |$`<$&>$'|\n"; # the special match vars print "'name' contains '$+{name}', 'nextchar' contains '$+{nextchar}'\n"; } else { print "No match: |$_|\n"; } }
bewuethr/ctci
llama_book/chapter08/chapter08_ex05.pl
Perl
mit
522
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my $dir = shift; die "Please provide a directory name to check\n" unless $dir; chdir $dir or die "Failed to enter the specified directory '$dir': $!\n"; if ( ! open(GIT_LS,'-|','git ls-files') ) { die "Failed to process 'git ls-files': $!\n"; } my %stats; while (my $file = <GIT_LS>) { chomp $file; if ( ! open(GIT_LOG,'-|',"git log --numstat $file") ) { die "Failed to process 'git log --numstat $file': $!\n"; } my $author; while (my $log_line = <GIT_LOG>) { if ( $log_line =~ m{^Author:\s*([^<]*?)\s*<([^>]*)>} ) { $author = lc($1); } elsif ( $log_line =~ m{^(\d+)\s+(\d+)\s+(.*)} ) { my $added = $1; my $removed = $2; my $file = $3; $stats{total}{by_author}{$author}{added} += $added; $stats{total}{by_author}{$author}{removed} += $removed; $stats{total}{by_author}{total}{added} += $added; $stats{total}{by_author}{total}{removed} += $removed; $stats{total}{by_file}{$file}{$author}{added} += $added; $stats{total}{by_file}{$file}{$author}{removed} += $removed; $stats{total}{by_file}{$file}{total}{added} += $added; $stats{total}{by_file}{$file}{total}{removed} += $removed; } } close GIT_LOG; if ( ! open(GIT_BLAME,'-|',"git blame -w $file") ) { die "Failed to process 'git blame -w $file': $!\n"; } while (my $log_line = <GIT_BLAME>) { if ( $log_line =~ m{\((.*?)\s+\d{4}} ) { my $author = $1; $stats{final}{by_author}{$author} ++; $stats{final}{by_file}{$file}{$author}++; $stats{final}{by_author}{total} ++; $stats{final}{by_file}{$file}{total} ++; $stats{final}{by_file}{$file}{total} ++; } } close GIT_BLAME; } close GIT_LS; print "Total lines committed by author by file\n"; printf "%25s %25s %8s %8s %9s\n",'file','author','added','removed','pct add'; foreach my $file (sort keys %{$stats{total}{by_file}}) { printf "%25s %4.0f%%\n",$file ,100*$stats{total}{by_file}{$file}{total}{added}/$stats{total}{by_author}{total}{added}; foreach my $author (sort keys %{$stats{total}{by_file}{$file}}) { next if $author eq 'total'; if ( $stats{total}{by_file}{$file}{total}{added} ) { printf "%25s %25s %8d %8d %8.0f%%\n",'', $author,@{$stats{total}{by_file}{$file}{$author}}{qw{added removed}} ,100*$stats{total}{by_file}{$file}{$author}{added}/$stats{total}{by_file}{$file}{total}{added}; } else { printf "%25s %25s %8d %8d\n",'', $author,@{$stats{total}{by_file}{$file}{$author}}{qw{added removed}} ; } } } print "\n"; print "Total lines in the final project by author by file\n"; printf "%25s %25s %8s %9s %9s\n",'file','author','final','percent', '% of all'; foreach my $file (sort keys %{$stats{final}{by_file}}) { printf "%25s %4.0f%%\n",$file ,100*$stats{final}{by_file}{$file}{total}/$stats{final}{by_author}{total}; foreach my $author (sort keys %{$stats{final}{by_file}{$file}}) { next if $author eq 'total'; printf "%25s %25s %8d %8.0f%% %8.0f%%\n",'', $author,$stats{final}{by_file}{$file}{$author} ,100*$stats{final}{by_file}{$file}{$author}/$stats{final}{by_file}{$file}{total} ,100*$stats{final}{by_file}{$file}{$author}/$stats{final}{by_author}{total} ; } } print "\n"; print "Total lines committed by author\n"; printf "%25s %8s %8s %9s\n",'author','added','removed','pct add'; foreach my $author (sort keys %{$stats{total}{by_author}}) { next if $author eq 'total'; printf "%25s %8d %8d %8.0f%%\n",$author,@{$stats{total}{by_author}{$author}}{qw{added removed}} ,100*$stats{total}{by_author}{$author}{added}/$stats{total}{by_author}{total}{added}; }; print "\n"; print "Total lines in the final project by author\n"; printf "%25s %8s %9s\n",'author','final','percent'; foreach my $author (sort keys %{$stats{final}{by_author}}) { printf "%25s %8d %8.0f%%\n",$author,$stats{final}{by_author}{$author} ,100*$stats{final}{by_author}{$author}/$stats{final}{by_author}{total}; }
KnightHawk3/packr
sloc.pl
Perl
mit
4,351
%% Extension designed to fetch news and download updates from swi-prolog.org :- module(news, [ news/1 ,news_abort/0 ]). :- use_module(dispatch). :- use_module(info). :- use_module(config). :- use_module(submodules/html). :- use_module(submodules/web). :- use_module(submodules/utils). :- use_module(library(sgml)). :- use_module(library(http/http_open)). :- use_module(library(http/json)). :- use_module(library(xpath)). :- use_module(library(uri)). :- use_module(library(solution_sequences)). :- use_module(library(persistency)). :- dynamic current_date/1. :- dynamic current_day/1. :- persistent heading(headline:string). :- persistent version(type:atom, number:string). :- persistent kjv_quote(quote:string). :- persistent commit(comm:string). :- persistent issue(state:string, number:integer). % TBD: Use the foundation of this module to prime the state infrastructure target("##prolog", "yesbot"). news_link("http://www.swi-prolog.org/news/archive"). version_link(stable, "http://www.swi-prolog.org/download/stable/src/"). version_link(development, "http://www.swi-prolog.org/download/devel/src/"). kjv_link("http://kingjamesprogramming.tumblr.com/"). swi_commit_link("https://api.github.com/repos/SWI-Prolog/swipl-devel/commits"). swi_issue_link("https://api.github.com/repos/SWI-Prolog/swipl-devel/issues?state=all"). news_time_limit(3600). % Time limit in seconds news(Msg) :- catch(once(thread_property(news, _)), E, ignore(news_trigger(Msg))). news_trigger(Msg) :- with_mutex(news_db, ( db_attach('extensions/news.db', []), ignore(news_(Msg)) ) ). %% news_(Msg:compound) is semidet. % % True if the message is a ping message to the bot, then run a persistent % thread in the background that checks for news and download updates. news_(Msg) :- Msg = msg("PING", _, _), thread_create(news_loop, _, [alias(news), detached(true)]). %% news_loop is det. % % Check the news feed on startup and evalute for side effects. Check the news feed % every hour for updates. This predicate is always true. news_loop :- news_time_limit(Limit), get_time(T1), stamp_date_time(T1, DateTime, local), date_time_value(day, DateTime, Day), date_time_value(date, DateTime, Date), ( current_day(_) -> retractall(current_day(_)), asserta(current_day(Day)) ; asserta(current_day(Day)) ), ( current_date(_) -> retractall(current_date(_)), asserta(current_date(Date)) ; asserta(current_date(Date)) ), ignore(news_feed(Date)), news_check(T1, Limit). %% news_check(+T1:float, +Limit:integer) is det. news_check(T1, Limit) :- sleep(0.05), compare_days, get_time(T2), Delta is T2 - T1, ( Delta >= Limit, current_date(Date) -> ignore(news_feed(Date)), get_time(T0), news_check(T0, Limit) ; news_check(T1, Limit) ). %% news_feed(+Date) is det. % % Attempt to scan swi-prolog.org news archive for updates and display to channel. news_feed(Date) :- target(Chan, _), news_link(Link), ignore(fetch_news(Link, Chan)), ignore(fetch_version), ignore(fetch_king_james), ignore(fetch_swi_commit(Date)), ignore(fetch_swi_issue). %% fetch_news(+Link:string, +Chan:string) is semidet. fetch_news(Link, Chan) :- setup_call_cleanup( http_open(Link, Stream, [timeout(20)]), valid_post(Stream, Chan, Link), close(Stream) ). %% fetch_version is det. fetch_version :- ignore(get_latest_version(stable)), ignore(get_latest_version(development)). %% fetch_king_james is semidet. % % Get the latest quote from the KJV site and pass the Quote to fetch_kv_quote/1. fetch_king_james :- kjv_link(Link), setup_call_cleanup( http_open(Link, Stream, []), ( load_html(Stream, Structure, []), xpath_chk(Structure, //blockquote(normalize_space), Content), fetch_kjv_quote(Content) ), close(Stream) ). %% fetch_kjv_quote(+Content:atom) is det. % % Analyzes quotes, and only displays quotes that have not yet been displayed. fetch_kjv_quote(Content) :- target(Chan, _), atom_string(Content, Quote), ( % Found a stored quote kjv_quote(Q) -> ( Q \= Quote -> % Current quote is not equal to stored quote % Therefore delete the old one and store the new one % Display it to the channel retract_kjv_quote(Q), assert_kjv_quote(Quote), priv_msg(Quote, Chan) ; % Current quote is the same as the stored one % Therefore succeed and don't do anything true ) ; % No stored quote found % Therefore store the new quote and display to channel assert_kjv_quote(Quote), priv_msg(Quote, Chan) ). %% fetch_swi_commit(+Date) is semidet. % % Access swi commits on github using the JSON API. Then print commits. fetch_swi_commit(Date) :- swi_commit_link(Link), setup_call_cleanup( http_open(Link, Stream, []), json_read_dict(Stream, Array), close(Stream) ), print_swi_commit(Array, Date). %% print_swi_commit(+Array, +Date) is failure. % % Print commits only for this day. Only prints commits that haven't been printed. print_swi_commit(Array, Date) :- member(Dict, Array), is_dict(Dict), parse_time(Dict.commit.committer.date, Stamp), stamp_date_time(Stamp, DateTime, local), date_time_value(date, DateTime, Date), Msg = Dict.commit.message, \+commit(Msg), assert_commit(Msg), target(Chan, _), format(string(MsgLine),"swipl-devel commit: ~s~n", [Msg]), format(string(Url),"~s", [Dict.html_url]), priv_msg(MsgLine, Chan, [at_most(7)]), sleep(1), priv_msg(Url, Chan, [at_most(7)]), sleep(1), priv_msg("***", Chan), sleep(5), fail. %% fetch_swi_issue is semidet. % % Access swi issues on github using the JSON API. Then print issues. fetch_swi_issue :- swi_issue_link(Link), setup_call_cleanup( http_open(Link, Stream, []), json_read_dict(Stream, Array), close(Stream) ), print_swi_issue(Array). %% print_swi_issue(+Array) is failure. % % Print issue opens and closes. Only issue events that haven't been printed. print_swi_issue(Array) :- member(Dict, Array), is_dict(Dict), % If pull_request is not a key then P is null (normal issue) catch(P = Dict.pull_request, _E, P = null), handle_swi_issue(P, Dict). handle_swi_issue(null, Dict) :- Args = [Dict.html_url, Dict.title, Dict.body], S = Dict.state, N = Dict.number, handle_stored_issue(S, N, "swipl-devel issue ", Args), fail. handle_swi_issue(Paragraph, Dict) :- Paragraph \= null, Args = [Dict.html_url, Dict.title, Dict.body], S = Dict.state, N = Dict.number, handle_stored_issue(S, N, "swipl-devel pull-request ", Args), fail. handle_stored_issue(State, N, Title, Args) :- target(Chan, _), ( issue(Stored, N) -> ( State \= Stored -> % If the issue has been mentioned in channel, but the state has changed % retract the issue, and assert it with the new state, while also % the issue again. retract_issue(Stored, N), assert_issue(State, N), format(string(Report), "~s[~s]~n~s~n~s~n~s", [Title,State|Args]), priv_msg(Report, Chan, [at_most(7)]), sleep(1), priv_msg("***", Chan), sleep(5) ; % Do nothing if the issue has been mentioned and the state is identical true ) ; State = "open" -> % If the issue hasn't been mentioned and the state is open % assert the issue and mention it in the channel format(string(Report), "~s[~s]~n~s~n~s~n~s", [Title,State|Args]), assert_issue(State, N), priv_msg(Report, Chan, [at_most(7)]), sleep(1), priv_msg("***", Chan), sleep(5) ; % If the issue hasn't been mentioned and has a closed state, do nothing. true ). %% valid_post(+Stream, +Chan:string, +Link:string) is semidet. % % Run IO side effects for all valid posts. Valid posts are posts that are % determined to match the current day of the month for this year. valid_post(Stream, Chan, Link) :- count_valid_posts(Stream, Count, Content), forall( limit(Count, xpath(Content, //h2(@class='post-title', normalize_space), H)), ( atom_string(H, Heading), \+heading(Heading), assert_heading(Heading), format(string(Report), "News Update: ~s~n***", [Heading]), priv_msg(Report, Chan), sleep(5) ) ), Count > 0, send_msg(priv_msg, Link, Chan). %% count_valid_posts(+Stream, -Count:integer, -Content) is det. % % Count the total amount of valid posts (match today's date) and unify content % with the parsed html. count_valid_posts(Stream, Count, Content) :- load_html(Stream, Content, []), get_time(Stamp2), aggregate_all(count, ( xpath(Content, //span(@class=date, normalize_space), Text), parse_time(Text, Stamp1), stamp_date_time(Stamp1, Dt1, local), stamp_date_time(Stamp2, Dt2, local), date_time_value(date, Dt1, Same), date_time_value(date, Dt2, Same)), Count). %% compare_days is semidet. % % Get current day stored in the database and compare it to the system's realtime % representation of the current day. If they are unequal then assert the systems % representation; nothing should be done otherwise. NOTE: this predicate should % be deterministic, but is not because current_day/1 is dynamic. Therefore an % error should be thrown if there is failure. So for now, unti this is resolved, % this predicate should be marked as semidet. This predicate also retracts all % headings from the persistent database daily, for cleanup/maintenence purposes. compare_days :- current_day(Current), get_time(Time), stamp_date_time(Time, DateTime, local), date_time_value(day, DateTime, Day), date_time_value(date, DateTime, Date), ( Current = Day -> true ; retractall(current_day(_)), retractall(current_date(_)), asserta(current_date(Date)), asserta(current_day(Day)), db_sync(gc), retractall_heading(_), retractall_commit(_) ). %% get_latest_version(+Type:atom) is semidet. % % Attempt to retrieve latest software version of Type (either stable or devel) % and display the result via IO side effects. get_latest_version(Type) :- target(Chan, _), version_link(Type, Link), latest_version(Link, Version), format(string(Update), "New ~a build available for download: version ~s", [Type, Version]), ( \+version(Type, Version) -> retractall_version(Type, _), assert_version(Type, Version), send_msg(priv_msg, Update, Chan), ( Type = stable -> send_msg(priv_msg, "http://www.swi-prolog.org/download/stable", Chan) ; send_msg(priv_msg, "http://www.swi-prolog.org/download/devel", Chan) ), priv_msg("***", Chan) ; true ). %% latest_version(+Link:string, -Version:string) is semidet. % % Parse a link and attempt to extract the last (latest version) file that is % available for download in the appropriate formatted table in the swi site. latest_version(Link, Version) :- setup_call_cleanup( http_open(Link, Stream, [timeout(20)]), load_html(Stream, Content, []), close(Stream) ), findall(File, ( xpath(Content, //tr(@class=Parity), Row), memberchk(Parity, [odd,even]), xpath(Row, //a(normalize_space), File) ), Files ), String_is_num = (\Str^number_string(_, Str)), split_string(last $ Files, "-.", "", Latest), include(String_is_num, Latest, Nums), atomic_list_concat(Nums, ., Atom), atom_string(Atom, Version). %% news_abort is det. % % Kill the thread when no longer needed. Exposed in the API. news_abort :- core:thread_signal(news, throw(abort)).
logicmoo/yesbot
extensions/news.pl
Perl
mit
11,597
#!/usr/bin/env perl #*************************************************************************** # _ _ ____ _ # Project ___| | | | _ \| | # / __| | | | |_) | | # | (__| |_| | _ <| |___ # \___|\___/|_| \_\_____| # # Copyright (C) 1998 - 2012, Daniel Stenberg, <daniel@haxx.se>, et al. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://curl.haxx.se/docs/copyright.html. # # You may opt to use, copy, modify, merge, publish, distribute and/or sell # copies of the Software, and permit persons to whom the Software is # furnished to do so, under the terms of the COPYING file. # # This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY # KIND, either express or implied. # ########################################################################### # This is a server designed for the curl test suite. # # In December 2009 we started remaking the server to support more protocols # that are similar in spirit. Like POP3, IMAP and SMTP in addition to the FTP # it already supported since a long time. Note that it still only supports one # protocol per invoke. You need to start multiple servers to support multiple # protocols simultaneously. # # It is meant to exercise curl, it is not meant to be a fully working # or even very standard compliant server. # # You may optionally specify port on the command line, otherwise it'll # default to port 8921. # # All socket/network/TCP related stuff is done by the 'sockfilt' program. # BEGIN { @INC=(@INC, $ENV{'srcdir'}, '.'); # sub second timestamping needs Time::HiRes eval { no warnings "all"; require Time::HiRes; import Time::HiRes qw( gettimeofday ); } } use strict; use warnings; use IPC::Open2; require "getpart.pm"; require "ftp.pm"; require "directories.pm"; use serverhelp qw( servername_str server_pidfilename server_logfilename mainsockf_pidfilename mainsockf_logfilename datasockf_pidfilename datasockf_logfilename ); #********************************************************************** # global vars... # my $verbose = 0; # set to 1 for debugging my $idstr = ""; # server instance string my $idnum = 1; # server instance number my $ipvnum = 4; # server IPv number (4 or 6) my $proto = 'ftp'; # default server protocol my $srcdir; # directory where ftpserver.pl is located my $srvrname; # server name for presentation purposes my $path = '.'; my $logdir = $path .'/log'; #********************************************************************** # global vars used for server address and primary listener port # my $port = 8921; # default primary listener port my $listenaddr = '127.0.0.1'; # default address for listener port #********************************************************************** # global vars used for file names # my $pidfile; # server pid file name my $logfile; # server log file name my $mainsockf_pidfile; # pid file for primary connection sockfilt process my $mainsockf_logfile; # log file for primary connection sockfilt process my $datasockf_pidfile; # pid file for secondary connection sockfilt process my $datasockf_logfile; # log file for secondary connection sockfilt process #********************************************************************** # global vars used for server logs advisor read lock handling # my $SERVERLOGS_LOCK = 'log/serverlogs.lock'; my $serverlogslocked = 0; #********************************************************************** # global vars used for child processes PID tracking # my $sfpid; # PID for primary connection sockfilt process my $slavepid; # PID for secondary connection sockfilt process #********************************************************************** # global typeglob filehandle vars to read/write from/to sockfilters # local *SFREAD; # used to read from primary connection local *SFWRITE; # used to write to primary connection local *DREAD; # used to read from secondary connection local *DWRITE; # used to write to secondary connection my $sockfilt_timeout = 5; # default timeout for sockfilter eXsysreads #********************************************************************** # global vars which depend on server protocol selection # my %commandfunc; # protocol command specific function callbacks my %displaytext; # text returned to client before callback runs my @welcome; # text returned to client upon connection #********************************************************************** # global vars customized for each test from the server commands file # my $ctrldelay; # set if server should throttle ctrl stream my $datadelay; # set if server should throttle data stream my $retrweirdo; # set if ftp server should use RETRWEIRDO my $retrnosize; # set if ftp server should use RETRNOSIZE my $pasvbadip; # set if ftp server should use PASVBADIP my $nosave; # set if ftp server should not save uploaded data my $nodataconn; # set if ftp srvr doesn't establish or accepts data channel my $nodataconn425; # set if ftp srvr doesn't establish data ch and replies 425 my $nodataconn421; # set if ftp srvr doesn't establish data ch and replies 421 my $nodataconn150; # set if ftp srvr doesn't establish data ch and replies 150 my $support_capa; # set if server supports capability command my $support_auth; # set if server supports authentication command my %customreply; # my %customcount; # my %delayreply; # #********************************************************************** # global variables for to test ftp wildcardmatching or other test that # need flexible LIST responses.. and corresponding files. # $ftptargetdir is keeping the fake "name" of LIST directory. # my $ftplistparserstate; my $ftptargetdir; #********************************************************************** # global variables used when running a ftp server to keep state info # relative to the secondary or data sockfilt process. Values of these # variables should only be modified using datasockf_state() sub, given # that they are closely related and relationship is a bit awkward. # my $datasockf_state = 'STOPPED'; # see datasockf_state() sub my $datasockf_mode = 'none'; # ['none','active','passive'] my $datasockf_runs = 'no'; # ['no','yes'] my $datasockf_conn = 'no'; # ['no','yes'] #********************************************************************** # global vars used for signal handling # my $got_exit_signal = 0; # set if program should finish execution ASAP my $exit_signal; # first signal handled in exit_signal_handler #********************************************************************** # exit_signal_handler will be triggered to indicate that the program # should finish its execution in a controlled way as soon as possible. # For now, program will also terminate from within this handler. # sub exit_signal_handler { my $signame = shift; # For now, simply mimic old behavior. killsockfilters($proto, $ipvnum, $idnum, $verbose); unlink($pidfile); if($serverlogslocked) { $serverlogslocked = 0; clear_advisor_read_lock($SERVERLOGS_LOCK); } exit; } #********************************************************************** # logmsg is general message logging subroutine for our test servers. # sub logmsg { my $now; # sub second timestamping needs Time::HiRes if($Time::HiRes::VERSION) { my ($seconds, $usec) = gettimeofday(); my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($seconds); $now = sprintf("%02d:%02d:%02d.%06d ", $hour, $min, $sec, $usec); } else { my $seconds = time(); my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($seconds); $now = sprintf("%02d:%02d:%02d ", $hour, $min, $sec); } if(open(LOGFILEFH, ">>$logfile")) { print LOGFILEFH $now; print LOGFILEFH @_; close(LOGFILEFH); } } sub ftpmsg { # append to the server.input file open(INPUT, ">>log/server$idstr.input") || logmsg "failed to open log/server$idstr.input\n"; print INPUT @_; close(INPUT); # use this, open->print->close system only to make the file # open as little as possible, to make the test suite run # better on windows/cygwin } #********************************************************************** # eXsysread is a wrapper around perl's sysread() function. This will # repeat the call to sysread() until it has actually read the complete # number of requested bytes or an unrecoverable condition occurs. # On success returns a positive value, the number of bytes requested. # On failure or timeout returns zero. # sub eXsysread { my $FH = shift; my $scalar = shift; my $nbytes = shift; my $timeout = shift; # A zero timeout disables eXsysread() time limit # my $time_limited = 0; my $timeout_rest = 0; my $start_time = 0; my $nread = 0; my $rc; $$scalar = ""; if((not defined $nbytes) || ($nbytes < 1)) { logmsg "Error: eXsysread() failure: " . "length argument must be positive\n"; return 0; } if((not defined $timeout) || ($timeout < 0)) { logmsg "Error: eXsysread() failure: " . "timeout argument must be zero or positive\n"; return 0; } if($timeout > 0) { # caller sets eXsysread() time limit $time_limited = 1; $timeout_rest = $timeout; $start_time = int(time()); } while($nread < $nbytes) { if($time_limited) { eval { local $SIG{ALRM} = sub { die "alarm\n"; }; alarm $timeout_rest; $rc = sysread($FH, $$scalar, $nbytes - $nread, $nread); alarm 0; }; $timeout_rest = $timeout - (int(time()) - $start_time); if($timeout_rest < 1) { logmsg "Error: eXsysread() failure: timed out\n"; return 0; } } else { $rc = sysread($FH, $$scalar, $nbytes - $nread, $nread); } if($got_exit_signal) { logmsg "Error: eXsysread() failure: signalled to die\n"; return 0; } if(not defined $rc) { if($!{EINTR}) { logmsg "Warning: retrying sysread() interrupted system call\n"; next; } if($!{EAGAIN}) { logmsg "Warning: retrying sysread() due to EAGAIN\n"; next; } if($!{EWOULDBLOCK}) { logmsg "Warning: retrying sysread() due to EWOULDBLOCK\n"; next; } logmsg "Error: sysread() failure: $!\n"; return 0; } if($rc < 0) { logmsg "Error: sysread() failure: returned negative value $rc\n"; return 0; } if($rc == 0) { logmsg "Error: sysread() failure: read zero bytes\n"; return 0; } $nread += $rc; } return $nread; } #********************************************************************** # read_mainsockf attempts to read the given amount of output from the # sockfilter which is in use for the main or primary connection. This # reads untranslated sockfilt lingo which may hold data read from the # main or primary socket. On success returns 1, otherwise zero. # sub read_mainsockf { my $scalar = shift; my $nbytes = shift; my $timeout = shift; # Optional argument, if zero blocks indefinitively my $FH = \*SFREAD; if(not defined $timeout) { $timeout = $sockfilt_timeout + ($nbytes >> 12); } if(eXsysread($FH, $scalar, $nbytes, $timeout) != $nbytes) { my ($fcaller, $lcaller) = (caller)[1,2]; logmsg "Error: read_mainsockf() failure at $fcaller " . "line $lcaller. Due to eXsysread() failure\n"; return 0; } return 1; } #********************************************************************** # read_datasockf attempts to read the given amount of output from the # sockfilter which is in use for the data or secondary connection. This # reads untranslated sockfilt lingo which may hold data read from the # data or secondary socket. On success returns 1, otherwise zero. # sub read_datasockf { my $scalar = shift; my $nbytes = shift; my $timeout = shift; # Optional argument, if zero blocks indefinitively my $FH = \*DREAD; if(not defined $timeout) { $timeout = $sockfilt_timeout + ($nbytes >> 12); } if(eXsysread($FH, $scalar, $nbytes, $timeout) != $nbytes) { my ($fcaller, $lcaller) = (caller)[1,2]; logmsg "Error: read_datasockf() failure at $fcaller " . "line $lcaller. Due to eXsysread() failure\n"; return 0; } return 1; } sub sysread_or_die { my $FH = shift; my $scalar = shift; my $length = shift; my $fcaller; my $lcaller; my $result; $result = sysread($$FH, $$scalar, $length); if(not defined $result) { ($fcaller, $lcaller) = (caller)[1,2]; logmsg "Failed to read input\n"; logmsg "Error: $srvrname server, sysread error: $!\n"; logmsg "Exited from sysread_or_die() at $fcaller " . "line $lcaller. $srvrname server, sysread error: $!\n"; killsockfilters($proto, $ipvnum, $idnum, $verbose); unlink($pidfile); if($serverlogslocked) { $serverlogslocked = 0; clear_advisor_read_lock($SERVERLOGS_LOCK); } exit; } elsif($result == 0) { ($fcaller, $lcaller) = (caller)[1,2]; logmsg "Failed to read input\n"; logmsg "Error: $srvrname server, read zero\n"; logmsg "Exited from sysread_or_die() at $fcaller " . "line $lcaller. $srvrname server, read zero\n"; killsockfilters($proto, $ipvnum, $idnum, $verbose); unlink($pidfile); if($serverlogslocked) { $serverlogslocked = 0; clear_advisor_read_lock($SERVERLOGS_LOCK); } exit; } return $result; } sub startsf { my $mainsockfcmd = "./server/sockfilt " . "--ipv$ipvnum --port $port " . "--pidfile \"$mainsockf_pidfile\" " . "--logfile \"$mainsockf_logfile\""; $sfpid = open2(*SFREAD, *SFWRITE, $mainsockfcmd); print STDERR "$mainsockfcmd\n" if($verbose); print SFWRITE "PING\n"; my $pong; sysread_or_die(\*SFREAD, \$pong, 5); if($pong !~ /^PONG/) { logmsg "Failed sockfilt command: $mainsockfcmd\n"; killsockfilters($proto, $ipvnum, $idnum, $verbose); unlink($pidfile); if($serverlogslocked) { $serverlogslocked = 0; clear_advisor_read_lock($SERVERLOGS_LOCK); } die "Failed to start sockfilt!"; } } sub sockfilt { my $l; foreach $l (@_) { printf SFWRITE "DATA\n%04x\n", length($l); print SFWRITE $l; } } sub sockfiltsecondary { my $l; foreach $l (@_) { printf DWRITE "DATA\n%04x\n", length($l); print DWRITE $l; } } # Send data to the client on the control stream, which happens to be plain # stdout. sub sendcontrol { if(!$ctrldelay) { # spit it all out at once sockfilt @_; } else { my $a = join("", @_); my @a = split("", $a); for(@a) { sockfilt $_; select(undef, undef, undef, 0.01); } } my $log; foreach $log (@_) { my $l = $log; $l =~ s/\r/[CR]/g; $l =~ s/\n/[LF]/g; logmsg "> \"$l\"\n"; } } #********************************************************************** # Send data to the FTP client on the data stream when data connection # is actually established. Given that this sub should only be called # when a data connection is supposed to be established, calling this # without a data connection is an indication of weak logic somewhere. # sub senddata { my $l; if($datasockf_conn eq 'no') { logmsg "WARNING: Detected data sending attempt without DATA channel\n"; foreach $l (@_) { logmsg "WARNING: Data swallowed: $l\n" } return; } foreach $l (@_) { if(!$datadelay) { # spit it all out at once sockfiltsecondary $l; } else { # pause between each byte for (split(//,$l)) { sockfiltsecondary $_; select(undef, undef, undef, 0.01); } } } } #********************************************************************** # protocolsetup initializes the 'displaytext' and 'commandfunc' hashes # for the given protocol. References to protocol command callbacks are # stored in 'commandfunc' hash, and text which will be returned to the # client before the command callback runs is stored in 'displaytext'. # sub protocolsetup { my $proto = $_[0]; if($proto eq 'ftp') { %commandfunc = ( 'PORT' => \&PORT_ftp, 'EPRT' => \&PORT_ftp, 'LIST' => \&LIST_ftp, 'NLST' => \&NLST_ftp, 'PASV' => \&PASV_ftp, 'CWD' => \&CWD_ftp, 'PWD' => \&PWD_ftp, 'EPSV' => \&PASV_ftp, 'RETR' => \&RETR_ftp, 'SIZE' => \&SIZE_ftp, 'REST' => \&REST_ftp, 'STOR' => \&STOR_ftp, 'APPE' => \&STOR_ftp, # append looks like upload 'MDTM' => \&MDTM_ftp, ); %displaytext = ( 'USER' => '331 We are happy you popped in!', 'PASS' => '230 Welcome you silly person', 'PORT' => '200 You said PORT - I say FINE', 'TYPE' => '200 I modify TYPE as you wanted', 'LIST' => '150 here comes a directory', 'NLST' => '150 here comes a directory', 'CWD' => '250 CWD command successful.', 'SYST' => '215 UNIX Type: L8', # just fake something 'QUIT' => '221 bye bye baby', # just reply something 'MKD' => '257 Created your requested directory', 'REST' => '350 Yeah yeah we set it there for you', 'DELE' => '200 OK OK OK whatever you say', 'RNFR' => '350 Received your order. Please provide more', 'RNTO' => '250 Ok, thanks. File renaming completed.', 'NOOP' => '200 Yes, I\'m very good at doing nothing.', 'PBSZ' => '500 PBSZ not implemented', 'PROT' => '500 PROT not implemented', ); @welcome = ( '220- _ _ ____ _ '."\r\n", '220- ___| | | | _ \| | '."\r\n", '220- / __| | | | |_) | | '."\r\n", '220- | (__| |_| | _ <| |___ '."\r\n", '220 \___|\___/|_| \_\_____|'."\r\n" ); } elsif($proto eq 'pop3') { %commandfunc = ( 'CAPA' => \&CAPA_pop3, 'AUTH' => \&AUTH_pop3, 'RETR' => \&RETR_pop3, 'LIST' => \&LIST_pop3, ); %displaytext = ( 'USER' => '+OK We are happy you popped in!', 'PASS' => '+OK Access granted', 'QUIT' => '+OK byebye', ); @welcome = ( ' _ _ ____ _ '."\r\n", ' ___| | | | _ \| | '."\r\n", ' / __| | | | |_) | | '."\r\n", ' | (__| |_| | _ <| |___ '."\r\n", ' \___|\___/|_| \_\_____|'."\r\n", '+OK cURL POP3 server ready to serve'."\r\n" ); } elsif($proto eq 'imap') { %commandfunc = ( 'FETCH' => \&FETCH_imap, 'SELECT' => \&SELECT_imap, ); %displaytext = ( 'LOGIN' => ' OK We are happy you popped in!', 'SELECT' => ' OK selection done', 'LOGOUT' => ' OK thanks for the fish', ); @welcome = ( ' _ _ ____ _ '."\r\n", ' ___| | | | _ \| | '."\r\n", ' / __| | | | |_) | | '."\r\n", ' | (__| |_| | _ <| |___ '."\r\n", ' \___|\___/|_| \_\_____|'."\r\n", '* OK cURL IMAP server ready to serve'."\r\n" ); } elsif($proto eq 'smtp') { %commandfunc = ( 'DATA' => \&DATA_smtp, 'RCPT' => \&RCPT_smtp, ); %displaytext = ( 'EHLO' => "250-SIZE\r\n250 Welcome visitor, stay a while staaaaaay forever", 'MAIL' => '200 Note taken', 'RCPT' => '200 Receivers accepted', 'QUIT' => '200 byebye', ); @welcome = ( '220- _ _ ____ _ '."\r\n", '220- ___| | | | _ \| | '."\r\n", '220- / __| | | | |_) | | '."\r\n", '220- | (__| |_| | _ <| |___ '."\r\n", '220 \___|\___/|_| \_\_____|'."\r\n" ); } } sub close_dataconn { my ($closed)=@_; # non-zero if already disconnected my $datapid = processexists($datasockf_pidfile); logmsg "=====> Closing $datasockf_mode DATA connection...\n"; if(!$closed) { if($datapid > 0) { logmsg "Server disconnects $datasockf_mode DATA connection\n"; print DWRITE "DISC\n"; my $i; sysread DREAD, $i, 5; } else { logmsg "Server finds $datasockf_mode DATA connection already ". "disconnected\n"; } } else { logmsg "Server knows $datasockf_mode DATA connection is already ". "disconnected\n"; } if($datapid > 0) { print DWRITE "QUIT\n"; waitpid($datapid, 0); unlink($datasockf_pidfile) if(-f $datasockf_pidfile); logmsg "DATA sockfilt for $datasockf_mode data channel quits ". "(pid $datapid)\n"; } else { logmsg "DATA sockfilt for $datasockf_mode data channel already ". "dead\n"; } logmsg "=====> Closed $datasockf_mode DATA connection\n"; datasockf_state('STOPPED'); } ################ ################ SMTP commands ################ # what set by "RCPT" my $smtp_rcpt; sub DATA_smtp { my $testno; if($smtp_rcpt =~ /^TO:(.*)/) { $testno = $1; } else { return; # failure } if($testno eq "<verifiedserver>") { sendcontrol "554 WE ROOLZ: $$\r\n"; return 0; # don't wait for data now } else { $testno =~ s/^([^0-9]*)([0-9]+).*/$2/; sendcontrol "354 Show me the mail\r\n"; } logmsg "===> rcpt $testno was $smtp_rcpt\n"; my $filename = "log/upload.$testno"; logmsg "Store test number $testno in $filename\n"; open(FILE, ">$filename") || return 0; # failed to open output my $line; my $ulsize=0; my $disc=0; my $raw; while (5 == (sysread \*SFREAD, $line, 5)) { if($line eq "DATA\n") { my $i; my $eob; sysread \*SFREAD, $i, 5; my $size = 0; if($i =~ /^([0-9a-fA-F]{4})\n/) { $size = hex($1); } read_mainsockf(\$line, $size); $ulsize += $size; print FILE $line if(!$nosave); $raw .= $line; if($raw =~ /\x0d\x0a\x2e\x0d\x0a/) { # end of data marker! $eob = 1; } logmsg "> Appending $size bytes to file\n"; if($eob) { logmsg "Found SMTP EOB marker\n"; last; } } elsif($line eq "DISC\n") { # disconnect! $disc=1; last; } else { logmsg "No support for: $line"; last; } } if($nosave) { print FILE "$ulsize bytes would've been stored here\n"; } close(FILE); sendcontrol "250 OK, data received!\r\n"; logmsg "received $ulsize bytes upload\n"; } sub RCPT_smtp { my ($args) = @_; $smtp_rcpt = $args; } ################ ################ IMAP commands ################ # global to allow the command functions to read it my $cmdid; # what was picked by SELECT my $selected; sub SELECT_imap { my ($testno) = @_; my @data; my $size; logmsg "SELECT_imap got test $testno\n"; $selected = $testno; return 0; } sub FETCH_imap { my ($testno) = @_; my @data; my $size; logmsg "FETCH_imap got test $testno\n"; $testno = $selected; if($testno =~ /^verifiedserver$/) { # this is the secret command that verifies that this actually is # the curl test server my $response = "WE ROOLZ: $$\r\n"; if($verbose) { print STDERR "FTPD: We returned proof we are the test server\n"; } $data[0] = $response; logmsg "return proof we are we\n"; } else { logmsg "retrieve a mail\n"; $testno =~ s/^([^0-9]*)//; my $testpart = ""; if ($testno > 10000) { $testpart = $testno % 10000; $testno = int($testno / 10000); } # send mail content loadtest("$srcdir/data/test$testno"); @data = getpart("reply", "data$testpart"); } for (@data) { $size += length($_); } sendcontrol "* FETCH starts {$size}\r\n"; for my $d (@data) { sendcontrol $d; } sendcontrol "$cmdid OK FETCH completed\r\n"; return 0; } ################ ################ POP3 commands ################ sub CAPA_pop3 { my ($testno) = @_; my @data = (); if(!$support_capa) { push @data, "-ERR Unsupported command: 'CAPA'\r\n"; } else { push @data, "+OK List of capabilities follows\r\n"; push @data, "USER\r\n"; if($support_auth) { push @data, "SASL UNKNOWN\r\n"; } push @data, "IMPLEMENTATION POP3 pingpong test server\r\n"; push @data, ".\r\n"; } for my $d (@data) { sendcontrol $d; } return 0; } sub AUTH_pop3 { my ($testno) = @_; my @data = (); if(!$support_auth) { push @data, "-ERR Unsupported command: 'AUTH'\r\n"; } else { push @data, "+OK List of supported mechanisms follows\r\n"; push @data, "UNKNOWN\r\n"; push @data, ".\r\n"; } for my $d (@data) { sendcontrol $d; } return 0; } sub RETR_pop3 { my ($testno) = @_; my @data; if($testno =~ /^verifiedserver$/) { # this is the secret command that verifies that this actually is # the curl test server my $response = "WE ROOLZ: $$\r\n"; if($verbose) { print STDERR "FTPD: We returned proof we are the test server\n"; } $data[0] = $response; logmsg "return proof we are we\n"; } else { logmsg "retrieve a mail\n"; $testno =~ s/^([^0-9]*)//; my $testpart = ""; if ($testno > 10000) { $testpart = $testno % 10000; $testno = int($testno / 10000); } # send mail content loadtest("$srcdir/data/test$testno"); @data = getpart("reply", "data$testpart"); } sendcontrol "+OK Mail transfer starts\r\n"; for my $d (@data) { sendcontrol $d; } # end with the magic 3-byte end of mail marker, assumes that the # mail body ends with a CRLF! sendcontrol ".\r\n"; return 0; } sub LIST_pop3 { # this is a built-in fake-message list my @pop3list=( "1 100\r\n", "2 4294967400\r\n", # > 4 GB "4 200\r\n", # Note that message 3 is a simulated "deleted" message ); logmsg "retrieve a message list\n"; sendcontrol "+OK Listing starts\r\n"; for my $d (@pop3list) { sendcontrol $d; } # end with the magic 3-byte end of listing marker sendcontrol ".\r\n"; return 0; } ################ ################ FTP commands ################ my $rest=0; sub REST_ftp { $rest = $_[0]; logmsg "Set REST position to $rest\n" } sub switch_directory_goto { my $target_dir = $_; if(!$ftptargetdir) { $ftptargetdir = "/"; } if($target_dir eq "") { $ftptargetdir = "/"; } elsif($target_dir eq "..") { if($ftptargetdir eq "/") { $ftptargetdir = "/"; } else { $ftptargetdir =~ s/[[:alnum:]]+\/$//; } } else { $ftptargetdir .= $target_dir . "/"; } } sub switch_directory { my $target_dir = $_[0]; if($target_dir eq "/") { $ftptargetdir = "/"; } else { my @dirs = split("/", $target_dir); for(@dirs) { switch_directory_goto($_); } } } sub CWD_ftp { my ($folder, $fullcommand) = $_[0]; switch_directory($folder); if($ftptargetdir =~ /^\/fully_simulated/) { $ftplistparserstate = "enabled"; } else { undef $ftplistparserstate; } } sub PWD_ftp { my $mydir; $mydir = $ftptargetdir ? $ftptargetdir : "/"; if($mydir ne "/") { $mydir =~ s/\/$//; } sendcontrol "257 \"$mydir\" is current directory\r\n"; } sub LIST_ftp { # print "150 ASCII data connection for /bin/ls (193.15.23.1,59196) (0 bytes)\r\n"; # this is a built-in fake-dir ;-) my @ftpdir=("total 20\r\n", "drwxr-xr-x 8 98 98 512 Oct 22 13:06 .\r\n", "drwxr-xr-x 8 98 98 512 Oct 22 13:06 ..\r\n", "drwxr-xr-x 2 98 98 512 May 2 1996 .NeXT\r\n", "-r--r--r-- 1 0 1 35 Jul 16 1996 README\r\n", "lrwxrwxrwx 1 0 1 7 Dec 9 1999 bin -> usr/bin\r\n", "dr-xr-xr-x 2 0 1 512 Oct 1 1997 dev\r\n", "drwxrwxrwx 2 98 98 512 May 29 16:04 download.html\r\n", "dr-xr-xr-x 2 0 1 512 Nov 30 1995 etc\r\n", "drwxrwxrwx 2 98 1 512 Oct 30 14:33 pub\r\n", "dr-xr-xr-x 5 0 1 512 Oct 1 1997 usr\r\n"); if($datasockf_conn eq 'no') { if($nodataconn425) { sendcontrol "150 Opening data connection\r\n"; sendcontrol "425 Can't open data connection\r\n"; } elsif($nodataconn421) { sendcontrol "150 Opening data connection\r\n"; sendcontrol "421 Connection timed out\r\n"; } elsif($nodataconn150) { sendcontrol "150 Opening data connection\r\n"; # client shall timeout } else { # client shall timeout } return 0; } if($ftplistparserstate) { @ftpdir = ftp_contentlist($ftptargetdir); } logmsg "pass LIST data on data connection\n"; for(@ftpdir) { senddata $_; } close_dataconn(0); sendcontrol "226 ASCII transfer complete\r\n"; return 0; } sub NLST_ftp { my @ftpdir=("file", "with space", "fake", "..", " ..", "funny", "README"); if($datasockf_conn eq 'no') { if($nodataconn425) { sendcontrol "150 Opening data connection\r\n"; sendcontrol "425 Can't open data connection\r\n"; } elsif($nodataconn421) { sendcontrol "150 Opening data connection\r\n"; sendcontrol "421 Connection timed out\r\n"; } elsif($nodataconn150) { sendcontrol "150 Opening data connection\r\n"; # client shall timeout } else { # client shall timeout } return 0; } logmsg "pass NLST data on data connection\n"; for(@ftpdir) { senddata "$_\r\n"; } close_dataconn(0); sendcontrol "226 ASCII transfer complete\r\n"; return 0; } sub MDTM_ftp { my $testno = $_[0]; my $testpart = ""; if ($testno > 10000) { $testpart = $testno % 10000; $testno = int($testno / 10000); } loadtest("$srcdir/data/test$testno"); my @data = getpart("reply", "mdtm"); my $reply = $data[0]; chomp $reply if($reply); if($reply && ($reply =~ /^[+-]?\d+$/) && ($reply < 0)) { sendcontrol "550 $testno: no such file.\r\n"; } elsif($reply) { sendcontrol "$reply\r\n"; } else { sendcontrol "500 MDTM: no such command.\r\n"; } return 0; } sub SIZE_ftp { my $testno = $_[0]; if($ftplistparserstate) { my $size = wildcard_filesize($ftptargetdir, $testno); if($size == -1) { sendcontrol "550 $testno: No such file or directory.\r\n"; } else { sendcontrol "213 $size\r\n"; } return 0; } if($testno =~ /^verifiedserver$/) { my $response = "WE ROOLZ: $$\r\n"; my $size = length($response); sendcontrol "213 $size\r\n"; return 0; } if($testno =~ /(\d+)\/?$/) { $testno = $1; } else { print STDERR "SIZE_ftp: invalid test number: $testno\n"; return 1; } my $testpart = ""; if($testno > 10000) { $testpart = $testno % 10000; $testno = int($testno / 10000); } loadtest("$srcdir/data/test$testno"); my @data = getpart("reply", "size"); my $size = $data[0]; if($size) { if($size > -1) { sendcontrol "213 $size\r\n"; } else { sendcontrol "550 $testno: No such file or directory.\r\n"; } } else { $size=0; @data = getpart("reply", "data$testpart"); for(@data) { $size += length($_); } if($size) { sendcontrol "213 $size\r\n"; } else { sendcontrol "550 $testno: No such file or directory.\r\n"; } } return 0; } sub RETR_ftp { my ($testno) = @_; if($datasockf_conn eq 'no') { if($nodataconn425) { sendcontrol "150 Opening data connection\r\n"; sendcontrol "425 Can't open data connection\r\n"; } elsif($nodataconn421) { sendcontrol "150 Opening data connection\r\n"; sendcontrol "421 Connection timed out\r\n"; } elsif($nodataconn150) { sendcontrol "150 Opening data connection\r\n"; # client shall timeout } else { # client shall timeout } return 0; } if($ftplistparserstate) { my @content = wildcard_getfile($ftptargetdir, $testno); if($content[0] == -1) { #file not found } else { my $size = length $content[1]; sendcontrol "150 Binary data connection for $testno ($size bytes).\r\n", senddata $content[1]; close_dataconn(0); sendcontrol "226 File transfer complete\r\n"; } return 0; } if($testno =~ /^verifiedserver$/) { # this is the secret command that verifies that this actually is # the curl test server my $response = "WE ROOLZ: $$\r\n"; my $len = length($response); sendcontrol "150 Binary junk ($len bytes).\r\n"; senddata "WE ROOLZ: $$\r\n"; close_dataconn(0); sendcontrol "226 File transfer complete\r\n"; if($verbose) { print STDERR "FTPD: We returned proof we are the test server\n"; } return 0; } $testno =~ s/^([^0-9]*)//; my $testpart = ""; if ($testno > 10000) { $testpart = $testno % 10000; $testno = int($testno / 10000); } loadtest("$srcdir/data/test$testno"); my @data = getpart("reply", "data$testpart"); my $size=0; for(@data) { $size += length($_); } my %hash = getpartattr("reply", "data$testpart"); if($size || $hash{'sendzero'}) { if($rest) { # move read pointer forward $size -= $rest; logmsg "REST $rest was removed from size, makes $size left\n"; $rest = 0; # reset REST offset again } if($retrweirdo) { sendcontrol "150 Binary data connection for $testno () ($size bytes).\r\n", "226 File transfer complete\r\n"; for(@data) { my $send = $_; senddata $send; } close_dataconn(0); $retrweirdo=0; # switch off the weirdo again! } else { my $sz = "($size bytes)"; if($retrnosize) { $sz = "size?"; } sendcontrol "150 Binary data connection for $testno () $sz.\r\n"; for(@data) { my $send = $_; senddata $send; } close_dataconn(0); sendcontrol "226 File transfer complete\r\n"; } } else { sendcontrol "550 $testno: No such file or directory.\r\n"; } return 0; } sub STOR_ftp { my $testno=$_[0]; my $filename = "log/upload.$testno"; if($datasockf_conn eq 'no') { if($nodataconn425) { sendcontrol "150 Opening data connection\r\n"; sendcontrol "425 Can't open data connection\r\n"; } elsif($nodataconn421) { sendcontrol "150 Opening data connection\r\n"; sendcontrol "421 Connection timed out\r\n"; } elsif($nodataconn150) { sendcontrol "150 Opening data connection\r\n"; # client shall timeout } else { # client shall timeout } return 0; } logmsg "STOR test number $testno in $filename\n"; sendcontrol "125 Gimme gimme gimme!\r\n"; open(FILE, ">$filename") || return 0; # failed to open output my $line; my $ulsize=0; my $disc=0; while (5 == (sysread DREAD, $line, 5)) { if($line eq "DATA\n") { my $i; sysread DREAD, $i, 5; my $size = 0; if($i =~ /^([0-9a-fA-F]{4})\n/) { $size = hex($1); } read_datasockf(\$line, $size); #print STDERR " GOT: $size bytes\n"; $ulsize += $size; print FILE $line if(!$nosave); logmsg "> Appending $size bytes to file\n"; } elsif($line eq "DISC\n") { # disconnect! $disc=1; last; } else { logmsg "No support for: $line"; last; } } if($nosave) { print FILE "$ulsize bytes would've been stored here\n"; } close(FILE); close_dataconn($disc); logmsg "received $ulsize bytes upload\n"; sendcontrol "226 File transfer complete\r\n"; return 0; } sub PASV_ftp { my ($arg, $cmd)=@_; my $pasvport; my $bindonly = ($nodataconn) ? '--bindonly' : ''; # kill previous data connection sockfilt when alive if($datasockf_runs eq 'yes') { killsockfilters($proto, $ipvnum, $idnum, $verbose, 'data'); logmsg "DATA sockfilt for $datasockf_mode data channel killed\n"; } datasockf_state('STOPPED'); logmsg "====> Passive DATA channel requested by client\n"; logmsg "DATA sockfilt for passive data channel starting...\n"; # We fire up a new sockfilt to do the data transfer for us. my $datasockfcmd = "./server/sockfilt " . "--ipv$ipvnum $bindonly --port 0 " . "--pidfile \"$datasockf_pidfile\" " . "--logfile \"$datasockf_logfile\""; $slavepid = open2(\*DREAD, \*DWRITE, $datasockfcmd); if($nodataconn) { datasockf_state('PASSIVE_NODATACONN'); } else { datasockf_state('PASSIVE'); } print STDERR "$datasockfcmd\n" if($verbose); print DWRITE "PING\n"; my $pong; sysread_or_die(\*DREAD, \$pong, 5); if($pong =~ /^FAIL/) { logmsg "DATA sockfilt said: FAIL\n"; logmsg "DATA sockfilt for passive data channel failed\n"; logmsg "DATA sockfilt not running\n"; datasockf_state('STOPPED'); sendcontrol "500 no free ports!\r\n"; return; } elsif($pong !~ /^PONG/) { logmsg "DATA sockfilt unexpected response: $pong\n"; logmsg "DATA sockfilt for passive data channel failed\n"; logmsg "DATA sockfilt killed now\n"; killsockfilters($proto, $ipvnum, $idnum, $verbose, 'data'); logmsg "DATA sockfilt not running\n"; datasockf_state('STOPPED'); sendcontrol "500 no free ports!\r\n"; return; } logmsg "DATA sockfilt for passive data channel started (pid $slavepid)\n"; # Find out on what port we listen on or have bound my $i; print DWRITE "PORT\n"; # READ the response code sysread_or_die(\*DREAD, \$i, 5); # READ the response size sysread_or_die(\*DREAD, \$i, 5); my $size = 0; if($i =~ /^([0-9a-fA-F]{4})\n/) { $size = hex($1); } # READ the response data read_datasockf(\$i, $size); # The data is in the format # IPvX/NNN if($i =~ /IPv(\d)\/(\d+)/) { # FIX: deal with IP protocol version $pasvport = $2; } if(!$pasvport) { logmsg "DATA sockfilt unknown listener port\n"; logmsg "DATA sockfilt for passive data channel failed\n"; logmsg "DATA sockfilt killed now\n"; killsockfilters($proto, $ipvnum, $idnum, $verbose, 'data'); logmsg "DATA sockfilt not running\n"; datasockf_state('STOPPED'); sendcontrol "500 no free ports!\r\n"; return; } if($nodataconn) { my $str = nodataconn_str(); logmsg "DATA sockfilt for passive data channel ($str) bound on port ". "$pasvport\n"; } else { logmsg "DATA sockfilt for passive data channel listens on port ". "$pasvport\n"; } if($cmd ne "EPSV") { # PASV reply my $p=$listenaddr; $p =~ s/\./,/g; if($pasvbadip) { $p="1,2,3,4"; } sendcontrol sprintf("227 Entering Passive Mode ($p,%d,%d)\n", int($pasvport/256), int($pasvport%256)); } else { # EPSV reply sendcontrol sprintf("229 Entering Passive Mode (|||%d|)\n", $pasvport); } logmsg "Client has been notified that DATA conn ". "will be accepted on port $pasvport\n"; if($nodataconn) { my $str = nodataconn_str(); logmsg "====> Client fooled ($str)\n"; return; } eval { local $SIG{ALRM} = sub { die "alarm\n" }; # assume swift operations unless explicitly slow alarm ($datadelay?20:10); # Wait for 'CNCT' my $input; # FIX: Monitor ctrl conn for disconnect while(sysread(DREAD, $input, 5)) { if($input !~ /^CNCT/) { # we wait for a connected client logmsg "Odd, we got $input from client\n"; next; } logmsg "Client connects to port $pasvport\n"; last; } alarm 0; }; if ($@) { # timed out logmsg "$srvrname server timed out awaiting data connection ". "on port $pasvport\n"; logmsg "accept failed or connection not even attempted\n"; logmsg "DATA sockfilt killed now\n"; killsockfilters($proto, $ipvnum, $idnum, $verbose, 'data'); logmsg "DATA sockfilt not running\n"; datasockf_state('STOPPED'); return; } else { logmsg "====> Client established passive DATA connection ". "on port $pasvport\n"; } return; } # # Support both PORT and EPRT here. # sub PORT_ftp { my ($arg, $cmd) = @_; my $port; my $addr; # kill previous data connection sockfilt when alive if($datasockf_runs eq 'yes') { killsockfilters($proto, $ipvnum, $idnum, $verbose, 'data'); logmsg "DATA sockfilt for $datasockf_mode data channel killed\n"; } datasockf_state('STOPPED'); logmsg "====> Active DATA channel requested by client\n"; # We always ignore the given IP and use localhost. if($cmd eq "PORT") { if($arg !~ /(\d+),(\d+),(\d+),(\d+),(\d+),(\d+)/) { logmsg "DATA sockfilt for active data channel not started ". "(bad PORT-line: $arg)\n"; sendcontrol "500 silly you, go away\r\n"; return; } $port = ($5<<8)+$6; $addr = "$1.$2.$3.$4"; } # EPRT |2|::1|49706| elsif($cmd eq "EPRT") { if($arg !~ /(\d+)\|([^\|]+)\|(\d+)/) { logmsg "DATA sockfilt for active data channel not started ". "(bad EPRT-line: $arg)\n"; sendcontrol "500 silly you, go away\r\n"; return; } sendcontrol "200 Thanks for dropping by. We contact you later\r\n"; $port = $3; $addr = $2; } else { logmsg "DATA sockfilt for active data channel not started ". "(invalid command: $cmd)\n"; sendcontrol "500 we don't like $cmd now\r\n"; return; } if(!$port || $port > 65535) { logmsg "DATA sockfilt for active data channel not started ". "(illegal PORT number: $port)\n"; return; } if($nodataconn) { my $str = nodataconn_str(); logmsg "DATA sockfilt for active data channel not started ($str)\n"; datasockf_state('ACTIVE_NODATACONN'); logmsg "====> Active DATA channel not established\n"; return; } logmsg "DATA sockfilt for active data channel starting...\n"; # We fire up a new sockfilt to do the data transfer for us. my $datasockfcmd = "./server/sockfilt " . "--ipv$ipvnum --connect $port --addr \"$addr\" " . "--pidfile \"$datasockf_pidfile\" " . "--logfile \"$datasockf_logfile\""; $slavepid = open2(\*DREAD, \*DWRITE, $datasockfcmd); datasockf_state('ACTIVE'); print STDERR "$datasockfcmd\n" if($verbose); print DWRITE "PING\n"; my $pong; sysread_or_die(\*DREAD, \$pong, 5); if($pong =~ /^FAIL/) { logmsg "DATA sockfilt said: FAIL\n"; logmsg "DATA sockfilt for active data channel failed\n"; logmsg "DATA sockfilt not running\n"; datasockf_state('STOPPED'); # client shall timeout awaiting connection from server return; } elsif($pong !~ /^PONG/) { logmsg "DATA sockfilt unexpected response: $pong\n"; logmsg "DATA sockfilt for active data channel failed\n"; logmsg "DATA sockfilt killed now\n"; killsockfilters($proto, $ipvnum, $idnum, $verbose, 'data'); logmsg "DATA sockfilt not running\n"; datasockf_state('STOPPED'); # client shall timeout awaiting connection from server return; } logmsg "DATA sockfilt for active data channel started (pid $slavepid)\n"; logmsg "====> Active DATA channel connected to client port $port\n"; return; } #********************************************************************** # datasockf_state is used to change variables that keep state info # relative to the FTP secondary or data sockfilt process as soon as # one of the five possible stable states is reached. Variables that # are modified by this sub may be checked independently but should # not be changed except by calling this sub. # sub datasockf_state { my $state = $_[0]; if($state eq 'STOPPED') { # Data sockfilter initial state, not running, # not connected and not used. $datasockf_state = $state; $datasockf_mode = 'none'; $datasockf_runs = 'no'; $datasockf_conn = 'no'; } elsif($state eq 'PASSIVE') { # Data sockfilter accepted connection from client. $datasockf_state = $state; $datasockf_mode = 'passive'; $datasockf_runs = 'yes'; $datasockf_conn = 'yes'; } elsif($state eq 'ACTIVE') { # Data sockfilter has connected to client. $datasockf_state = $state; $datasockf_mode = 'active'; $datasockf_runs = 'yes'; $datasockf_conn = 'yes'; } elsif($state eq 'PASSIVE_NODATACONN') { # Data sockfilter bound port without listening, # client won't be able to establish data connection. $datasockf_state = $state; $datasockf_mode = 'passive'; $datasockf_runs = 'yes'; $datasockf_conn = 'no'; } elsif($state eq 'ACTIVE_NODATACONN') { # Data sockfilter does not even run, # client awaits data connection from server in vain. $datasockf_state = $state; $datasockf_mode = 'active'; $datasockf_runs = 'no'; $datasockf_conn = 'no'; } else { die "Internal error. Unknown datasockf state: $state!"; } } #********************************************************************** # nodataconn_str returns string of efective nodataconn command. Notice # that $nodataconn may be set alone or in addition to a $nodataconnXXX. # sub nodataconn_str { my $str; # order matters $str = 'NODATACONN' if($nodataconn); $str = 'NODATACONN425' if($nodataconn425); $str = 'NODATACONN421' if($nodataconn421); $str = 'NODATACONN150' if($nodataconn150); return "$str"; } #********************************************************************** # customize configures test server operation for each curl test, reading # configuration commands/parameters from server commands file each time # a new client control connection is established with the test server. # On success returns 1, otherwise zero. # sub customize { $ctrldelay = 0; # default is no throttling of the ctrl stream $datadelay = 0; # default is no throttling of the data stream $retrweirdo = 0; # default is no use of RETRWEIRDO $retrnosize = 0; # default is no use of RETRNOSIZE $pasvbadip = 0; # default is no use of PASVBADIP $nosave = 0; # default is to actually save uploaded data to file $nodataconn = 0; # default is to establish or accept data channel $nodataconn425 = 0; # default is to not send 425 without data channel $nodataconn421 = 0; # default is to not send 421 without data channel $nodataconn150 = 0; # default is to not send 150 without data channel $support_capa = 0; # default is to not support capability command $support_auth = 0; # default is to not support authentication command %customreply = (); # %customcount = (); # %delayreply = (); # open(CUSTOM, "<log/ftpserver.cmd") || return 1; logmsg "FTPD: Getting commands from log/ftpserver.cmd\n"; while(<CUSTOM>) { if($_ =~ /REPLY ([A-Za-z0-9+\/=]+) (.*)/) { $customreply{$1}=eval "qq{$2}"; logmsg "FTPD: set custom reply for $1\n"; } elsif($_ =~ /COUNT ([A-Z]+) (.*)/) { # we blank the customreply for this command when having # been used this number of times $customcount{$1}=$2; logmsg "FTPD: blank custom reply for $1 after $2 uses\n"; } elsif($_ =~ /DELAY ([A-Z]+) (\d*)/) { $delayreply{$1}=$2; logmsg "FTPD: delay reply for $1 with $2 seconds\n"; } elsif($_ =~ /SLOWDOWN/) { $ctrldelay=1; $datadelay=1; logmsg "FTPD: send response with 0.01 sec delay between each byte\n"; } elsif($_ =~ /RETRWEIRDO/) { logmsg "FTPD: instructed to use RETRWEIRDO\n"; $retrweirdo=1; } elsif($_ =~ /RETRNOSIZE/) { logmsg "FTPD: instructed to use RETRNOSIZE\n"; $retrnosize=1; } elsif($_ =~ /PASVBADIP/) { logmsg "FTPD: instructed to use PASVBADIP\n"; $pasvbadip=1; } elsif($_ =~ /NODATACONN425/) { # applies to both active and passive FTP modes logmsg "FTPD: instructed to use NODATACONN425\n"; $nodataconn425=1; $nodataconn=1; } elsif($_ =~ /NODATACONN421/) { # applies to both active and passive FTP modes logmsg "FTPD: instructed to use NODATACONN421\n"; $nodataconn421=1; $nodataconn=1; } elsif($_ =~ /NODATACONN150/) { # applies to both active and passive FTP modes logmsg "FTPD: instructed to use NODATACONN150\n"; $nodataconn150=1; $nodataconn=1; } elsif($_ =~ /NODATACONN/) { # applies to both active and passive FTP modes logmsg "FTPD: instructed to use NODATACONN\n"; $nodataconn=1; } elsif($_ =~ /SUPPORTCAPA/) { logmsg "FTPD: instructed to support CAPABILITY command\n"; $support_capa=1; } elsif($_ =~ /SUPPORTAUTH/) { logmsg "FTPD: instructed to support AUTHENTICATION command\n"; $support_auth=1; } elsif($_ =~ /NOSAVE/) { # don't actually store the file we upload - to be used when # uploading insanely huge amounts $nosave = 1; logmsg "FTPD: NOSAVE prevents saving of uploaded data\n"; } } close(CUSTOM); } #---------------------------------------------------------------------- #---------------------------------------------------------------------- #--------------------------- END OF SUBS ---------------------------- #---------------------------------------------------------------------- #---------------------------------------------------------------------- #********************************************************************** # Parse command line options # # Options: # # --verbose # verbose # --srcdir # source directory # --id # server instance number # --proto # server protocol # --pidfile # server pid file # --logfile # server log file # --ipv4 # server IP version 4 # --ipv6 # server IP version 6 # --port # server listener port # --addr # server address for listener port binding # while(@ARGV) { if($ARGV[0] eq '--verbose') { $verbose = 1; } elsif($ARGV[0] eq '--srcdir') { if($ARGV[1]) { $srcdir = $ARGV[1]; shift @ARGV; } } elsif($ARGV[0] eq '--id') { if($ARGV[1] && ($ARGV[1] =~ /^(\d+)$/)) { $idnum = $1 if($1 > 0); shift @ARGV; } } elsif($ARGV[0] eq '--proto') { if($ARGV[1] && ($ARGV[1] =~ /^(ftp|imap|pop3|smtp)$/)) { $proto = $1; shift @ARGV; } else { die "unsupported protocol $ARGV[1]"; } } elsif($ARGV[0] eq '--pidfile') { if($ARGV[1]) { $pidfile = $ARGV[1]; shift @ARGV; } } elsif($ARGV[0] eq '--logfile') { if($ARGV[1]) { $logfile = $ARGV[1]; shift @ARGV; } } elsif($ARGV[0] eq '--ipv4') { $ipvnum = 4; $listenaddr = '127.0.0.1' if($listenaddr eq '::1'); } elsif($ARGV[0] eq '--ipv6') { $ipvnum = 6; $listenaddr = '::1' if($listenaddr eq '127.0.0.1'); } elsif($ARGV[0] eq '--port') { if($ARGV[1] && ($ARGV[1] =~ /^(\d+)$/)) { $port = $1 if($1 > 1024); shift @ARGV; } } elsif($ARGV[0] eq '--addr') { if($ARGV[1]) { my $tmpstr = $ARGV[1]; if($tmpstr =~ /^(\d\d?\d?)\.(\d\d?\d?)\.(\d\d?\d?)\.(\d\d?\d?)$/) { $listenaddr = "$1.$2.$3.$4" if($ipvnum == 4); } elsif($ipvnum == 6) { $listenaddr = $tmpstr; $listenaddr =~ s/^\[(.*)\]$/$1/; } shift @ARGV; } } else { print STDERR "\nWarning: ftpserver.pl unknown parameter: $ARGV[0]\n"; } shift @ARGV; } #*************************************************************************** # Initialize command line option dependant variables # if(!$srcdir) { $srcdir = $ENV{'srcdir'} || '.'; } if(!$pidfile) { $pidfile = "$path/". server_pidfilename($proto, $ipvnum, $idnum); } if(!$logfile) { $logfile = server_logfilename($logdir, $proto, $ipvnum, $idnum); } $mainsockf_pidfile = "$path/". mainsockf_pidfilename($proto, $ipvnum, $idnum); $mainsockf_logfile = mainsockf_logfilename($logdir, $proto, $ipvnum, $idnum); if($proto eq 'ftp') { $datasockf_pidfile = "$path/". datasockf_pidfilename($proto, $ipvnum, $idnum); $datasockf_logfile = datasockf_logfilename($logdir, $proto, $ipvnum, $idnum); } $srvrname = servername_str($proto, $ipvnum, $idnum); $idstr = "$idnum" if($idnum > 1); protocolsetup($proto); $SIG{INT} = \&exit_signal_handler; $SIG{TERM} = \&exit_signal_handler; startsf(); logmsg sprintf("%s server listens on port IPv${ipvnum}/${port}\n", uc($proto)); open(PID, ">$pidfile"); print PID $$."\n"; close(PID); logmsg("logged pid $$ in $pidfile\n"); while(1) { # kill previous data connection sockfilt when alive if($datasockf_runs eq 'yes') { killsockfilters($proto, $ipvnum, $idnum, $verbose, 'data'); logmsg "DATA sockfilt for $datasockf_mode data channel killed now\n"; } datasockf_state('STOPPED'); # # We read 'sockfilt' commands. # my $input; logmsg "Awaiting input\n"; sysread_or_die(\*SFREAD, \$input, 5); if($input !~ /^CNCT/) { # we wait for a connected client logmsg "MAIN sockfilt said: $input"; next; } logmsg "====> Client connect\n"; set_advisor_read_lock($SERVERLOGS_LOCK); $serverlogslocked = 1; # flush data: $| = 1; &customize(); # read test control instructions sendcontrol @welcome; #remove global variables from last connection if($ftplistparserstate) { undef $ftplistparserstate; } if($ftptargetdir) { undef $ftptargetdir; } if($verbose) { for(@welcome) { print STDERR "OUT: $_"; } } my $full = ""; while(1) { my $i; # Now we expect to read DATA\n[hex size]\n[prot], where the [prot] # part only is FTP lingo. # COMMAND sysread_or_die(\*SFREAD, \$i, 5); if($i !~ /^DATA/) { logmsg "MAIN sockfilt said $i"; if($i =~ /^DISC/) { # disconnect last; } next; } # SIZE of data sysread_or_die(\*SFREAD, \$i, 5); my $size = 0; if($i =~ /^([0-9a-fA-F]{4})\n/) { $size = hex($1); } # data read_mainsockf(\$input, $size); ftpmsg $input; $full .= $input; # Loop until command completion next unless($full =~ /\r\n$/); # Remove trailing CRLF. $full =~ s/[\n\r]+$//; my $FTPCMD; my $FTPARG; if($proto eq "imap") { # IMAP is different with its identifier first on the command line unless(($full =~ /^([^ ]+) ([^ ]+) (.*)/) || ($full =~ /^([^ ]+) ([^ ]+)/)) { sendcontrol "$1 '$full': command not understood.\r\n"; last; } $cmdid=$1; # set the global variable $FTPCMD=$2; $FTPARG=$3; } elsif($full =~ /^([A-Z]{3,4})(\s(.*))?$/i) { $FTPCMD=$1; $FTPARG=$3; } elsif(($proto eq "smtp") && ($full =~ /^[A-Z0-9+\/]{0,512}={0,2}$/i)) { # SMTP long "commands" are base64 authentication data. $FTPCMD=$full; $FTPARG=""; } else { sendcontrol "500 '$full': command not understood.\r\n"; last; } logmsg "< \"$full\"\n"; if($verbose) { print STDERR "IN: $full\n"; } $full = ""; my $delay = $delayreply{$FTPCMD}; if($delay) { # just go sleep this many seconds! logmsg("Sleep for $delay seconds\n"); my $twentieths = $delay * 20; while($twentieths--) { select(undef, undef, undef, 0.05) unless($got_exit_signal); } } my $text; $text = $customreply{$FTPCMD}; my $fake = $text; if($text && ($text ne "")) { if($customcount{$FTPCMD} && (!--$customcount{$FTPCMD})) { # used enough number of times, now blank the customreply $customreply{$FTPCMD}=""; } } else { $text = $displaytext{$FTPCMD}; } my $check; if($text && ($text ne "")) { if($cmdid && ($cmdid ne "")) { sendcontrol "$cmdid$text\r\n"; } else { sendcontrol "$text\r\n"; } } else { $check=1; # no response yet } unless($fake && ($fake ne "")) { # only perform this if we're not faking a reply my $func = $commandfunc{$FTPCMD}; if($func) { &$func($FTPARG, $FTPCMD); $check=0; # taken care of } } if($check) { logmsg "$FTPCMD wasn't handled!\n"; if($proto eq 'pop3') { sendcontrol "-ERR $FTPCMD is not dealt with!\r\n"; } elsif($proto eq 'imap') { sendcontrol "$cmdid BAD $FTPCMD is not dealt with!\r\n"; } else { sendcontrol "500 $FTPCMD is not dealt with!\r\n"; } } } # while(1) logmsg "====> Client disconnected\n"; if($serverlogslocked) { $serverlogslocked = 0; clear_advisor_read_lock($SERVERLOGS_LOCK); } } killsockfilters($proto, $ipvnum, $idnum, $verbose); unlink($pidfile); if($serverlogslocked) { $serverlogslocked = 0; clear_advisor_read_lock($SERVERLOGS_LOCK); } exit;
FlashYoshi/YoutubePlaylistDownloader
curl-7.28.1/curl-7.28.1/tests/ftpserver.pl
Perl
mit
62,364
# Copyright 2020, Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. package Google::Ads::GoogleAds::V8::Services::KeywordPlanService::GenerateHistoricalMetricsRequest; use strict; use warnings; use base qw(Google::Ads::GoogleAds::BaseEntity); use Google::Ads::GoogleAds::Utils::GoogleAdsHelper; sub new { my ($class, $args) = @_; my $self = { aggregateMetrics => $args->{aggregateMetrics}, historicalMetricsOptions => $args->{historicalMetricsOptions}, keywordPlan => $args->{keywordPlan}}; # Delete the unassigned fields in this object for a more concise JSON payload remove_unassigned_fields($self, $args); bless $self, $class; return $self; } 1;
googleads/google-ads-perl
lib/Google/Ads/GoogleAds/V8/Services/KeywordPlanService/GenerateHistoricalMetricsRequest.pm
Perl
apache-2.0
1,208
=head1 LICENSE # Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute # Copyright [2016-2017] EMBL-European Bioinformatics Institute # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. =head1 CONTACT Please email comments or questions to the public Ensembl developers list at <http://lists.ensembl.org/mailman/listinfo/dev>. Questions may also be sent to the Ensembl help desk at <http://www.ensembl.org/Help/Contact>. =cut =head1 NAME Bio::EnsEMBL::Analysis::RunnableDB::CopyGenes - =head1 SYNOPSIS RunnableDB for copying genes from a source database to a target database. By default all the genes in the database COPY_SOURCE_DB are copied into the database COPY_TARGET_DB =head1 DESCRIPTION =head1 METHODS =cut package Bio::EnsEMBL::Analysis::RunnableDB::CopyGenes; use warnings ; use vars qw(@ISA); use strict; use Bio::EnsEMBL::Analysis::RunnableDB; use Bio::EnsEMBL::Analysis::RunnableDB::BaseGeneBuild; use Bio::EnsEMBL::Utils::Exception qw(throw warning); use Bio::EnsEMBL::Utils::Argument qw (rearrange); @ISA = qw(Bio::EnsEMBL::Analysis::RunnableDB::BaseGeneBuild); sub new{ my ($class,@args) = @_; my $self = $class->SUPER::new(@args); my ($given_source_db, $given_target_db, $given_biotype) = rearrange (['SOURCE_DB', 'TARGET_DB', 'BIOTYPE'], @args); #### Default values... $self->source_db_name("COPY_SOURCE_DB"); $self->target_db_name("COPY_TARGET_DB"); $self->biotype(""); ### ...are over-ridden by parameters given in analysis table... my $ph = $self->parameters_hash; $self->source_db_name($ph->{-source_db}) if exists $ph->{-source_db}; $self->target_db_name($ph->{-target_db}) if exists $ph->{-target_db}; $self->biotype($ph->{-biotype}) if exists $ph->{-biotype}; ### ...which are over-ridden by constructor arguments. $self->source_db_name($given_source_db) if defined $given_source_db; $self->target_db_name($given_target_db) if defined $given_target_db; $self->biotype($given_biotype) if defined $given_biotype; return $self; } #getter/setters sub source_db_name{ my ($self, $arg) = @_; if(defined $arg){ $self->{'source_db_name'} = $arg; } return $self->{'source_db_name'}; } sub target_db_name{ my ($self, $arg) = @_; if(defined $arg){ $self->{'target_db_name'} = $arg; } return $self->{'target_db_name'}; } sub biotype{ my ($self, $arg) = @_; if(defined $arg){ $self->{'biotype'} = $arg; } return $self->{'biotype'}; } ################################ sub fetch_input { my ($self) = @_; my $source_db = $self->get_dbadaptor($self->source_db_name); my $slice = $source_db->get_SliceAdaptor->fetch_by_name($self->input_id); # # total paranoia: fetch everything up front # my (@genes); my @target_genes; if($self->biotype){ @target_genes = @{$slice->get_all_Genes_by_type($self->biotype)}; }else{ @target_genes = @{$slice->get_all_Genes}; } foreach my $g (@target_genes) { foreach my $t (@{$g->get_all_Transcripts}) { foreach my $e (@{$t->get_all_Exons}) { $e->get_all_supporting_features; $e->stable_id; } my $tr = $t->translation; if (defined $tr) { $tr->stable_id; $tr->get_all_Attributes; $tr->get_all_DBEntries; $tr->get_all_ProteinFeatures; } $t->stable_id; $t->get_all_supporting_features; $t->get_all_DBEntries; $t->display_xref; $t->get_all_Attributes; } $g->stable_id; $g->get_all_DBEntries; $g->display_xref; $g->get_all_Attributes; push @genes, $g; } $self->output(\@genes); } ################################## sub write_output { my($self) = @_; my $target_db = $self->get_dbadaptor($self->target_db_name); my $g_adap = $target_db->get_GeneAdaptor; foreach my $g (@{$self->output}) { $g_adap->store($g); } return 1; } 1;
james-monkeyshines/ensembl-analysis
modules/Bio/EnsEMBL/Analysis/RunnableDB/CopyGenes.pm
Perl
apache-2.0
4,431
#! /usr/local/bin/perl use IO::Socket; use DBI; use Authen::Libwrap qw( hosts_ctl STRING_UNKNOWN); use Net::FTP; ## auth flush $|++; require "/export/home/rmail/bin/config.pl"; $remote_ip=$ENV{'TCPREMOTEIP'}; $local_host= `hostname`; chomp($local_host); if (!hosts_ctl("db_api", $local_host, $remote_ip)) { print STDOUT "-ERR ©Úµ´³s½u,Access denied\n"; exit; } # main process print STDOUT "+OK Welcome!\n"; $buf=<STDIN>; chomp($buf); $buf=~s /\r//g; if ($buf eq 'adduser') { # Add user print STDOUT "+OK Give me id pass domain ms\n"; $buf=<STDIN>; chomp($buf); $buf=~s /\r//g; ($id, $pass, $domain, $ms) =split(/\s+/, $buf); if ($id && $pass && $domain) { # get domain id and check id is availiable $dsn=sprintf("DBI:mysql:%s;host=%s", $DB{'mta'}{'name'}, $DB{'mta'}{'host'}); $dbh=DBI->connect($dsn, $DB{'mta'}{'user'}, $DB{'mta'}{'pass'}) || die_db($!); $sqlstmt=sprintf("select s_idx from DomainTransport where s_domain='%s'", $domain); $sth=$dbh->prepare($sqlstmt); $sth->execute(); if ($sth->rows != 1) { print STDOUT "-ERR ¸Óºô°ì¤£¦s¦b,no such domain\n"; $dbh->disconnect; close(STDOUT); exit; } ($domain_id)=($sth->fetchrow_array)[0]; # find ms's real hostnode $sqlstmt=sprintf("select s_nodename from HostMap where s_hostname='%s' AND s_domain=%d", $ms, $domain_id); $sth=$dbh->prepare($sqlstmt); $sth->execute(); if ($sth->rows != 1) { print STROUT "-ERR ¸Ó¶l¥ó¥D¾÷¤£¦s¦b,no such ms\n"; $dbh->disconnect; close(STDOUT); exit; } ($ms_node)=($sth->fetchrow_array)[0]; # check id is availiable if (substr($id, 0, 1) eq '.' || substr($id, 1, 1) eq '.' || substr($id, 0, 1) eq '_' || substr($id, 0, 1) eq '!' || length($id)<2) { print STDOUT "-ERR ±b¸¹®æ¦¡¿ù»~,wrong id!\n"; close(STDOUT); exit; } $sqlstmt=sprintf("select * from Suspend where s_mailid='%s' AND s_domain=%d", lc($id), $domain_id); $sth=$dbh->prepare($sqlstmt); $sth->execute(); if ($sth->rows != 0) { print STDOUT "-ERR ¸Ó±b¸¹¤w³QÃö³¬,this id was suspended\n"; $dbh->disconnect; close(STDOUT); exit; } $sqlstmt=sprintf("select * from MailCheck where s_mailid='%s' AND s_domain=%d", lc($id), $domain_id); $sth=$dbh->prepare($sqlstmt); $sth->execute(); if ($sth->rows != 0) { print STDOUT "-ERR ¸Ó±b¸¹¤w¦³¤H¥Ó½Ð,this id was existed\n"; $dbh->disconnect; close(STDOUT); exit; } print STDOUT "+OK $id $pass $domain_id $ms_node\n"; $buf=<STDIN>; chomp($buf); $buf=~s /\r//g; if ($buf eq 'go') { # do jobs # 1. add to mailcheck & mailpass $mbox=substr(lc($id), 0, 1)."/".substr(lc($id), 1, 1)."/".lc($id); $sqlstmt=sprintf("insert into MailCheck values ('%s', %d, '%s', '%s', 0)", lc($id), $domain_id, $ms, $mbox); $dbh->do($sqlstmt); $sqlstmt=sprintf("delete from MailPass where s_mailid='%s' AND s_domain=%d", lc($id), $domain_id); $dbh->do($sqlstmt); $sqlstmt=sprintf("insert into MailPass values ('%s', %d, ENCRYPT('%s'), '%s', NOW())", lc($id), $domain_id, $pass, $pass); $dbh->do($sqlstmt); # 2. build mailbox # TODO: call ms api to build mbox $socket=IO::Socket::INET->new( PeerAddr => $ms, PeerPort => $API{'ms'}{'port'}, Proto => 'tcp', Type => SOCK_STREAM) || die_socket($@); do { $buf=<$socket>; chomp($buf); $buf=~s /\r//g; ($buf)=(split(/\s+/, $buf))[0]; } while ($buf ne '+OK' && $buf ne '-ERR'); if ($buf eq '-ERR') { print STDOUT "-ERR ³sµ²¦øªA¾¹¥¢±Ñ,socket error\n"; close($socket); close(STDOUT); exit; } print $socket "createmdir\n"; do { $buf=<$socket>; chomp($buf); $buf=~s /\r//g; ($buf)=(split(/\s+/, $buf))[0]; } while ($buf ne '+OK' && $buf ne '-ERR'); if ($buf eq '-ERR') { print STDOUT "-ERR ¨Ï¥ÎªÌ¥Ø¿ý¦­¤w³Q«Ø¥ßdir already exist\n"; close($socket); close(STDOUT); exit; } $mpath=sprintf("/mnt/%s/%s", $ms, $mbox); print $socket "$mpath\n"; do { $buf=<$socket>; chomp($buf); $buf=~s /\r//g; ($buf)=(split(/\s+/, $buf))[0]; } while ($buf ne '+OK' && $buf ne '-ERR'); if ($buf eq '-ERR') { print STDOUT "-ERR ¥Î¤á¥Ø¿ý¦­¤w¦s¦b,dir already exist\n"; close($socket); close(STDOUT); exit; } $dsn=sprintf("DBI:mysql:%s;host=%s", $DB{'rec'}{'name'}, $DB{'rec'}{'host'}); $dbh2=DBI->connect($dsn, $DB{'rec'}{'user'}, $DB{'rec'}{'pass'}) || die_db($!); $sqlstmt=sprintf("delete from MailRecord_%s where s_mailid='%s' and s_domain=%d", substr(lc($id), 0, 1), lc($id), $domain_id); $dbh2->do($sqlstmt); $sqlstmt=sprintf("insert into MailRecord_%s values ('%s', %d, NOW(), NOW(), NOW(), '','','')", substr(lc($id), 0, 1), lc($id), $domain_id); $dbh2->do($sqlstmt); $dbh2->disconnect(); close($socket); print STDOUT "+OK §¹¦¨,Done!\n"; open(FH, ">>/tmp/api.log"); print FH "$id\tAdd\t".`date`; close(FH); } else { print STDOUT "-ERR API«ü¥O¿ù»~,Wrong command!\n"; $dbh->disconnect; close(STDOUT); exit; } close(STDOUT); exit; } else { print STDOUT "-ERR API°Ñ¼Æ®æ¦¡¦³»~,Format error!\n"; close(STDOUT); exit; } } elsif ($buf eq 'deluser') { print STDOUT "+OK Give me id domain\n"; $buf=<STDIN>; chomp($buf); $buf=~s /\r//g; ($id, $domain)=split(/\s+/,$buf); if ($id && $domain) { $dsn=sprintf("DBI:mysql:%s;host=%s", $DB{'mta'}{'name'}, $DB{'mta'}{'host'}); $dbh=DBI->connect($dsn, $DB{'mta'}{'user'}, $DB{'mta'}{'pass'}) || die_db($!); $sqlstmt=sprintf("select s_idx from DomainTransport where s_domain='%s'", $domain); $sth=$dbh->prepare($sqlstmt); $sth->execute(); if ($sth->rows != 1) { print STDOUT "-ERR no such domain\n"; $dbh->disconnect; close(STDOUT); exit; } ($domain_id)=($sth->fetchrow_array)[0]; $sqlstmt=sprintf("select s_mbox, s_mhost from MailCheck where s_mailid='%s' and s_domain=%d", lc($id), $domain_id); $sth=$dbh->prepare($sqlstmt); $sth->execute(); if ($sth->rows !=1) { print STDOUT "-ERR no such user\n"; $dbh->disconnect; close(STDOUT); exit; } ($s_mbox, $s_mhost)=($sth->fetchrow_array)[0,1]; $s_path=sprintf("/mnt/%s/%s", $s_mhost, $s_mbox); ## Do jobs # 1, delete all database record $sqlstmt=sprintf("delete from MailCheck where s_mailid='%s' and s_domain=%d", lc($id), $domain_id); $dbh->do($sqlstmt); $sqlstmt=sprintf("delete from MailPass where s_mailid='%s' and s_domain=%d", lc($id), $domain_id); $dbh->do($sqlstmt); # 2. delete mdir $socket=IO::Socket::INET->new( PeerAddr => $s_mhost, PeerPort => $API{'ms'}{'port'}, Proto => 'tcp', Type => SOCK_STREAM) || die_socket($@); do { $buf=<$socket>; chomp($buf); $buf=~s /\r//g; ($buf)=(split(/\s+/, $buf))[0]; } while ($buf ne '+OK' && $buf ne '-ERR'); if ($buf eq '-ERR') { print STDOUT "-ERR socket error\n"; close($socket); close(STDOUT); exit; } print $socket "deletemdir\n"; do { $buf=<$socket>; chomp($buf); $buf=~s /\r//g; ($buf)=(split(/\s+/, $buf))[0]; } while ($buf ne '+OK' && $buf ne '-ERR'); if ($buf eq '-ERR') { print STDOUT "-ERR socket error\n"; close($socket); close(STDOUT); exit; } print $socket "$s_path\n"; do { $buf=<$socket>; chomp($buf); $buf=~s /\r//g; ($buf)=(split(/\s+/, $buf))[0]; } while ($buf ne '+OK' && $buf ne '-ERR'); if ($buf eq '-ERR') { print STDOUT "-ERR socket error\n"; close($socket); close(STDOUT); exit; } close($socket); print STDOUT "+OK Done!\n"; open(FH, ">>/tmp/api.log"); print FH "$id\tDelete\t".`date`; close(FH); } else { print STDOUT "-ERR Wrong format!\n"; close(STDOUT); exit; } } elsif ($buf eq 'sususer') { print STDOUT "+OK Give me id domain\n"; $buf=<STDIN>; chomp($buf); $buf=~s /\r//g; ($id, $domain)=split(/\s+/,$buf); if ($id && $domain) { $dsn=sprintf("DBI:mysql:%s;host=%s", $DB{'mta'}{'name'}, $DB{'mta'}{'host'}); $dbh=DBI->connect($dsn, $DB{'mta'}{'user'}, $DB{'mta'}{'pass'}) || die_db($!); $sqlstmt=sprintf("select s_idx from DomainTransport where s_domain='%s'", $domain); $sth=$dbh->prepare($sqlstmt); $sth->execute(); if ($sth->rows != 1) { print STDOUT "-ERR no such domain\n"; $dbh->disconnect; close(STDOUT); exit; } ($domain_id)=($sth->fetchrow_array)[0]; $sqlstmt=sprintf("select * from MailCheck where s_mailid='%s' and s_domain=%d", lc($id), $domain_id); $sth=$dbh->prepare($sqlstmt); $sth->execute(); if ($sth->rows !=1) { print STDOUT "-ERR no such user\n"; $dbh->disconnect; close(STDOUT); exit; } ($s_mailid, $s_domain, $s_mhost, $s_mbox, $s_status) = $sth->fetchrow_array(); $s_path=sprintf("/mnt/%s/%s", $s_mhost, $s_mbox); # get rawpass $sqlstmt=sprintf("select s_rawpass from MailPass where s_mailid='%s' and s_domain=%d", lc($id), $domain_id); $sth=$dbh->prepare($sqlstmt); $sth->execute(); if ($sth->rows !=1) { print STDOUT "-ERR No password record?\n"; $dbh->disconnect; close(STDOUT); exit; } ($s_rawpass)=($sth->fetchrow_array)[0]; ## Do jobs # 1, delete all database record $sqlstmt=sprintf("delete from MailCheck where s_mailid='%s' and s_domain=%d", lc($id), $domain_id); $dbh->do($sqlstmt); $sqlstmt=sprintf("delete from MailPass where s_mailid='%s' and s_domain=%d", lc($id), $domain_id); $dbh->do($sqlstmt); # 2. Record $sqlstmt=sprintf("insert into Suspend values ('%s', %d, '%s', '%s', '%s', NOW())", $s_mailid, $s_domain, $s_rawpass, $s_mhost, $s_mbox); $dbh->do($sqlstmt); # 3. delete mdir # $socket=IO::Socket::INET->new( # PeerAddr => $s_mhost, # PeerPort => $API{'ms'}{'port'}, # Proto => 'tcp', # Type => SOCK_STREAM) # || die_socket($@); # do { # $buf=<$socket>; chomp($buf); $buf=~s /\r//g; # ($buf)=(split(/\s+/, $buf))[0]; # } while ($buf ne '+OK' && $buf ne '-ERR'); # if ($buf eq '-ERR') { # print STDOUT "-ERR socket error\n"; # close($socket); # close(STDOUT); # exit; # } # print $socket "deletemdir\n"; # do { # $buf=<$socket>; chomp($buf); $buf=~s /\r//g; # ($buf)=(split(/\s+/, $buf))[0]; # } while ($buf ne '+OK' && $buf ne '-ERR'); # if ($buf eq '-ERR') { # print STDOUT "-ERR socket error\n"; # close($socket); # close(STDOUT); # exit; # } # print $socket "$s_path\n"; # do { # $buf=<$socket>; chomp($buf); $buf=~s /\r//g; # ($buf)=(split(/\s+/, $buf))[0]; # } while ($buf ne '+OK' && $buf ne '-ERR'); # if ($buf eq '-ERR') { # print STDOUT "-ERR socket error\n"; # close($socket); # close(STDOUT); # exit; # } # # close($socket); print STDOUT "+OK Done!\n"; close(STDOUT); exit; } else { print STDOUT "-ERR Wrong format!\n"; close(STDOUT); exit; } } elsif ($buf eq 'unsususer') { print STDOUT "+OK Give me id domain\n"; $buf=<STDIN>; chomp($buf); $buf=~s /\r//g; ($id, $domain)=split(/\s+/,$buf); if ($id && $domain) { $dsn=sprintf("DBI:mysql:%s;host=%s", $DB{'mta'}{'name'}, $DB{'mta'}{'host'}); $dbh=DBI->connect($dsn, $DB{'mta'}{'user'}, $DB{'mta'}{'pass'}) || die_db($!); $sqlstmt=sprintf("select s_idx from DomainTransport where s_domain='%s'", $domain); $sth=$dbh->prepare($sqlstmt); $sth->execute(); if ($sth->rows != 1) { print STDOUT "-ERR no such domain\n"; $dbh->disconnect; close(STDOUT); exit; } ($domain_id)=($sth->fetchrow_array)[0]; $sqlstmt=sprintf("select s_mailid, s_domain, s_rawpass, s_mhost, s_mbox from Suspend where s_mailid='%s' and s_domain=%d", lc($id), $domain_id); $sth=$dbh->prepare($sqlstmt); $sth->execute(); if ($sth->rows !=1) { print STDOUT "-ERR no such user\n"; $dbh->disconnect; close(STDOUT); exit; } ($s_mailid, $s_domain, $s_rawpass, $s_mhost, $s_mbox)=$sth->fetchrow_array; $sqlstmt=sprintf("delete from Suspend where s_mailid='%s' and s_domain=%d", lc($id), $domain_id); $dbh->do($sqlstmt); ## Do jobs # 1, insert back all database record $sqlstmt=sprintf("insert into MailCheck values ('%s', %d, '%s', '%s', 0)", lc($id), $domain_id, $s_mhost, $s_mbox); $dbh->do($sqlstmt); $sqlstmt=sprintf("insert into MailPass values ('%s', %d, ENCRYPT('%s'), '%s', NOW())", lc($id), $domain_id, $s_rawpass, $s_rawpass); $dbh->do($sqlstmt); # 2. create mdir # $socket=IO::Socket::INET->new( # PeerAddr => $s_mhost, # PeerPort => $API{'ms'}{'port'}, # Proto => 'tcp', # Type => SOCK_STREAM) # || die_socket($@); # do { # $buf=<$socket>; chomp($buf); $buf=~s /\r//g; # ($buf)=(split(/\s+/, $buf))[0]; # } while ($buf ne '+OK' && $buf ne '-ERR'); # if ($buf eq '-ERR') { # print STDOUT "-ERR socket error\n"; # close($socket); # close(STDOUT); # exit; # } # print $socket "createmdir\n"; # # do { # $buf=<$socket>; chomp($buf); $buf=~s /\r//g; # ($buf)=(split(/\s+/, $buf))[0]; # } while ($buf ne '+OK' && $buf ne '-ERR'); # # if ($buf eq '-ERR') { # print STDOUT "-ERR socket error\n"; # close($socket); # close(STDOUT); # exit; # } # # $mpath=sprintf("/mnt/%s/%s", $s_mhost, $s_mbox); # print $socket "$mpath\n"; # # do { # $buf=<$socket>; chomp($buf); $buf=~s /\r//g; # ($buf)=(split(/\s+/, $buf))[0]; # } while ($buf ne '+OK' && $buf ne '-ERR'); # # if ($buf eq '-ERR') { # print STDOUT "-ERR socket error\n"; # close($socket); # close(STDOUT); # exit; # } $dsn=sprintf("DBI:mysql:%s;host=%s", $DB{'rec'}{'name'}, $DB{'rec'}{'host'}); $dbh2=DBI->connect($dsn, $DB{'rec'}{'user'}, $DB{'rec'}{'pass'}) || die_db($!); $sqlstmt=sprintf("delete from MailRecord_%s where s_mailid='%s' and s_domain=%d", substr(lc($id), 0, 1), lc($id), $domain_id); $dbh2->do($sqlstmt); $sqlstmt=sprintf("insert into MailRecord_%s values ('%s', %d, NOW(), NOW(), NOW(), '','','')", substr(lc($id), 0, 1), lc($id), $domain_id); $dbh2->do($sqlstmt); $dbh2->disconnect(); # close($socket); print STDOUT "+OK Done!\n"; close(STDOUT); exit; } else { print STDOUT "-ERR Wrong format!\n"; close(STDOUT); exit; } } elsif ($buf eq 'changepass') { print STDOUT "+OK Tell me <id> <domain> <new_password>\n"; $buf=<STDIN>; chomp($buf); $buf=~s /\r//g; ($id, $domain, $pass)=split(/\s+/, $buf); if ($id && $domain) { $dsn=sprintf("DBI:mysql:%s;host=%s", $DB{'mta'}{'name'}, $DB{'mta'}{'host'}); $dbh=DBI->connect($dsn, $DB{'mta'}{'user'}, $DB{'mta'}{'pass'}) || die_db($!); $sqlstmt=sprintf("select s_idx from DomainTransport where s_domain='%s'", $domain); $sth=$dbh->prepare($sqlstmt); $sth->execute(); if ($sth->rows != 1) { print STDOUT "-ERR no such domain\n"; $dbh->disconnect; close(STDOUT); exit; } ($domain_id)=($sth->fetchrow_array)[0]; $sqlstmt=sprintf("select * from MailPass where s_mailid='%s' and s_domain=%d", lc($id), $domain_id); $sth=$dbh->prepare($sqlstmt); $sth->execute(); if ($sth->rows !=1) { print STDOUT "-ERR no such user\n"; $dbh->disconnect; close(STDOUT); exit; } $sqlstmt=sprintf("update MailPass set s_rawpass='%s', s_encpass=ENCRYPT('%s') where s_mailid='%s' and s_domain=%d", $pass, $pass, $id, $domain_id); $dbh->do($sqlstmt); $dbh->disconnect(); print STDOUT "+OK done!\n"; close(STDOUT); } else { print STDOUT "-ERR format error!\n"; close(STDOUT); exit; } } else { print STDOUT "-ERR Wrong Command: $buf!\n"; close(STDOUT); exit; } sub die_db { $msg=$_[0]; print STDOUT "-ERR Cannot connect to database: $msg\n"; close(STDOUT); exit; } sub die_socket { $msg=$_[0]; print STDOUT "-ERR Cannot connect to api socket: $msg\n"; close(STDOUT); exit; }
TonyChengTW/PerlTools
db_api.pl
Perl
apache-2.0
15,659
use strict; use warnings; package KinoSearch::Test::TestUtils; use base qw( Exporter ); our @EXPORT_OK = qw( working_dir create_working_dir remove_working_dir create_index create_uscon_index test_index_loc persistent_test_index_loc init_test_index_loc get_uscon_docs utf8_test_strings test_analyzer doc_ids_from_td_coll modulo_set ); use KinoSearch; use KinoSearch::Test; use lib 'sample'; use KinoSearch::Test::USConSchema; use File::Spec::Functions qw( catdir catfile curdir ); use Encode qw( _utf8_off ); use File::Path qw( rmtree ); use Carp; my $working_dir = catfile( curdir(), 'kinosearch_test' ); # Return a directory within the system's temp directory where we will put all # testing scratch files. sub working_dir {$working_dir} sub create_working_dir { mkdir( $working_dir, 0700 ) or die "Can't mkdir '$working_dir': $!"; } # Verify that this user owns the working dir, then zap it. Returns true upon # success. sub remove_working_dir { return unless -d $working_dir; rmtree $working_dir; return 1; } # Return a location for a test index to be used by a single test file. If # the test file crashes it cannot clean up after itself, so we put the cleanup # routine in a single test file to be run at or near the end of the test # suite. sub test_index_loc { return catdir( $working_dir, 'test_index' ); } # Return a location for a test index intended to be shared by multiple test # files. It will be cleaned as above. sub persistent_test_index_loc { return catdir( $working_dir, 'persistent_test_index' ); } # Destroy anything left over in the test_index location, then create the # directory. Finally, return the path. sub init_test_index_loc { my $dir = test_index_loc(); rmtree $dir; die "Can't clean up '$dir'" if -e $dir; mkdir $dir or die "Can't mkdir '$dir': $!"; return $dir; } # Build a RAM index, using the supplied array of strings as source material. # The index will have a single field: "content". sub create_index { my $folder = KinoSearch::Store::RAMFolder->new; my $indexer = KinoSearch::Index::Indexer->new( index => $folder, schema => KinoSearch::Test::TestSchema->new, ); $indexer->add_doc( { content => $_ } ) for @_; $indexer->commit; return $folder; } # Slurp us constitition docs and build hashrefs. sub get_uscon_docs { my $uscon_dir = catdir( 'sample', 'us_constitution' ); opendir( my $uscon_dh, $uscon_dir ) or die "couldn't opendir '$uscon_dir': $!"; my @filenames = grep {/\.txt$/} sort readdir $uscon_dh; closedir $uscon_dh or die "couldn't closedir '$uscon_dir': $!"; my %docs; for my $filename (@filenames) { my $filepath = catfile( $uscon_dir, $filename ); open( my $fh, '<', $filepath ) or die "couldn't open file '$filepath': $!"; my $content = do { local $/; <$fh> }; $content =~ /(.*?)\n\n(.*)/s or die "Can't extract title/bodytext from '$filepath'"; my $title = $1; my $bodytext = $2; $bodytext =~ s/\s+/ /sg; my $category = $filename =~ /art/ ? 'article' : $filename =~ /amend/ ? 'amendment' : $filename =~ /preamble/ ? 'preamble' : confess "Can't derive category for $filename"; $docs{$filename} = { title => $title, bodytext => $bodytext, url => "/us_constitution/$filename", category => $category, }; } return \%docs; } sub create_uscon_index { my $folder = KinoSearch::Store::FSFolder->new( path => persistent_test_index_loc() ); my $schema = KinoSearch::Test::USConSchema->new; my $indexer = KinoSearch::Index::Indexer->new( schema => $schema, index => $folder, truncate => 1, create => 1, ); $indexer->add_doc( { content => "zz$_" } ) for ( 0 .. 10000 ); $indexer->commit; undef $indexer; $indexer = KinoSearch::Index::Indexer->new( schema => $schema, index => $folder, ); my $source_docs = get_uscon_docs(); $indexer->add_doc( { content => $_->{bodytext} } ) for values %$source_docs; $indexer->commit; undef $indexer; $indexer = KinoSearch::Index::Indexer->new( schema => $schema, index => $folder, ); my @chars = ( 'a' .. 'z' ); for ( 0 .. 1000 ) { my $content = ''; for my $num_words ( 1 .. int( rand(20) ) ) { for ( 1 .. ( int( rand(10) ) + 10 ) ) { $content .= @chars[ rand(@chars) ]; } $content .= ' '; } $indexer->add_doc( { content => $content } ); } $indexer->optimize; $indexer->commit; } # Return 3 strings useful for verifying UTF-8 integrity. sub utf8_test_strings { my $smiley = "\x{263a}"; my $not_a_smiley = $smiley; _utf8_off($not_a_smiley); my $frowny = $not_a_smiley; utf8::upgrade($frowny); return ( $smiley, $not_a_smiley, $frowny ); } # Verify an Analyzer's transform, transform_text, and split methods. sub test_analyzer { my ( $analyzer, $source, $expected, $message ) = @_; my $inversion = KinoSearch::Analysis::Inversion->new( text => $source ); $inversion = $analyzer->transform($inversion); my @got; while ( my $token = $inversion->next ) { push @got, $token->get_text; } Test::More::is_deeply( \@got, $expected, "analyze: $message" ); $inversion = $analyzer->transform_text($source); @got = (); while ( my $token = $inversion->next ) { push @got, $token->get_text; } Test::More::is_deeply( \@got, $expected, "transform_text: $message" ); @got = @{ $analyzer->split($source) }; Test::More::is_deeply( \@got, $expected, "split: $message" ); } # Extract all doc nums from a SortCollector. Return two sorted array refs: # by_score and by_id. sub doc_ids_from_td_coll { my $collector = shift; my @by_score; my $match_docs = $collector->pop_match_docs; my @by_score_then_id = map { $_->get_doc_id } sort { $b->get_score <=> $a->get_score || $a->get_doc_id <=> $b->get_doc_id } @$match_docs; my @by_id = sort { $a <=> $b } @by_score_then_id; return ( \@by_score_then_id, \@by_id ); } # Use a modulus to generate a set of numbers. sub modulo_set { my ( $interval, $max ) = @_; my @out; for ( my $doc = $interval; $doc < $max; $doc += $interval ) { push @out, $doc; } return \@out; } 1; __END__ __COPYRIGHT__ Copyright 2005-2011 Marvin Humphrey This program is free software; you can redistribute it and/or modify under the same terms as Perl itself.
gitpan/KinoSearch
buildlib/KinoSearch/Test/TestUtils.pm
Perl
apache-2.0
6,829
# # Author:: Adam Jacob (<adam@opscode.com>) # Copyright:: Copyright (c) 2008 Adam Jacob # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package Sid::Service::Controller::Agent; use strict; use warnings; use lib qw(/home/adam/src/sandbox/catalyst-svn/Catalyst-Action-REST/lib); use base 'Catalyst::Controller::REST'; use Exception::Class::TryCatch; =head1 NAME Sid::Service::Controller::Agent - Catalyst Controller =head1 DESCRIPTION Catalyst Controller. =head1 METHODS =cut sub single_agent : PathPart('agent') : Chained : Args(1) : ActionClass('REST') { } sub single_agent_GET { my ( $self, $c, $agent_id ) = @_; my $agent; eval { $agent = $c->model('Agent')->get( agent_id => $agent_id ); }; if ( catch my $e ) { return $self->status_not_found( $c, message => $e->message ); } $self->status_ok( $c, entity => $self->_uri_for_plugins( $c, $agent ), ); } sub single_agent_PUT { my ( $self, $c, $agent ) = @_; my $new_agent_data = $c->request->data; eval { $c->model('Agent')->create( agent => $new_agent_data, ); }; if ( catch my $e ) { return $self->status_bad_request( $c, message => $e->message ); } $self->status_accepted( $c, entity => { status => 'queued', location => $c->req->uri->as_string, }, ); } sub single_agent_POST { my ( $self, $c, $agent_id ) = @_; eval { $c->model('Agent')->update( agent => $c->request->data, ); }; if ( catch my $e ) { return $self->status_not_found( $c, message => $e->message ); } $self->status_accepted( $c, entity => { status => 'queued', }, ); } sub single_agent_DELETE { my ( $self, $c, $agent_id ) = @_; eval { $c->model('Agent')->remove( agent_id => $agent_id, ); }; if ( catch my $e ) { return $self->status_not_found( $c, message => $e->message ); } $self->status_accepted($c, entity => { status => 'queued' }, ); } sub agent : Path : Args(0) : ActionClass('REST') { } sub agent_GET { my ( $self, $c ) = @_; my $alist = $c->model('Agent')->list; foreach my $key ( keys( %{$alist} ) ) { $alist->{$key}->{'url'} = $c->uri_for( $c->action, $key )->as_string; } $self->status_ok( $c, entity => $alist, ); } sub _uri_for_plugins { my ( $self, $c, $agent ) = @_; for ( my $x = 0; $x < scalar( @{ $agent->{'plugins'} } ); $x++ ) { my $pv = $agent->{'plugins'}->[$x]; $agent->{'plugins'}->[$x] = $c->uri_for( $c->action, $agent->{'agent_id'}, $pv )->as_string; } return $agent; } =head1 AUTHOR Adam Jacob =head1 LICENSE This library is free software, you can redistribute it and/or modify it under the same terms as Perl itself. =cut 1;
adamhjk/sid
lib/Sid/Service/Controller/Agent.pm
Perl
apache-2.0
3,320
# Copyright 2020, Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. package Google::Ads::GoogleAds::V8::Enums::OptimizationGoalTypeEnum; use strict; use warnings; use Const::Exporter enums => [ UNSPECIFIED => "UNSPECIFIED", UNKNOWN => "UNKNOWN", CALL_CLICKS => "CALL_CLICKS", DRIVING_DIRECTIONS => "DRIVING_DIRECTIONS" ]; 1;
googleads/google-ads-perl
lib/Google/Ads/GoogleAds/V8/Enums/OptimizationGoalTypeEnum.pm
Perl
apache-2.0
869
# # Copyright 2018 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package hardware::server::dell::idrac::snmp::mode::components::coolingunit; use strict; use warnings; use hardware::server::dell::idrac::snmp::mode::components::resources qw(%map_status %map_state); my $mapping = { coolingUnitStateSettings => { oid => '.1.3.6.1.4.1.674.10892.5.4.700.10.1.4', map => \%map_state }, coolingUnitName => { oid => '.1.3.6.1.4.1.674.10892.5.4.700.10.1.7' }, coolingUnitStatus => { oid => '.1.3.6.1.4.1.674.10892.5.4.700.10.1.8', map => \%map_status }, }; my $oid_coolingUnitTableEntry = '.1.3.6.1.4.1.674.10892.5.4.700.10.1'; sub load { my ($self) = @_; push @{$self->{request}}, { oid => $oid_coolingUnitTableEntry }; } sub check { my ($self) = @_; $self->{output}->output_add(long_msg => "Checking cooling units"); $self->{components}->{coolingunit} = {name => 'cooling units', total => 0, skip => 0}; return if ($self->check_filter(section => 'coolingunit')); foreach my $oid ($self->{snmp}->oid_lex_sort(keys %{$self->{results}->{$oid_coolingUnitTableEntry}})) { next if ($oid !~ /^$mapping->{coolingUnitStatus}->{oid}\.(.*)$/); my $instance = $1; my $result = $self->{snmp}->map_instance(mapping => $mapping, results => $self->{results}->{$oid_coolingUnitTableEntry}, instance => $instance); next if ($self->check_filter(section => 'coolingunit', instance => $instance)); $self->{components}->{coolingunit}->{total}++; $self->{output}->output_add(long_msg => sprintf("cooling unit '%s' status is '%s' [instance = %s] [state = %s]", $result->{coolingUnitName}, $result->{coolingUnitStatus}, $instance, $result->{coolingUnitStateSettings})); my $exit = $self->get_severity(label => 'default.state', section => 'coolingunit.state', value => $result->{coolingUnitStateSettings}); if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) { $self->{output}->output_add(severity => $exit, short_msg => sprintf("Cooling unit '%s' state is '%s'", $result->{coolingUnitName}, $result->{coolingUnitStateSettings})); next; } $exit = $self->get_severity(label => 'default.status', section => 'coolingunit.status', value => $result->{coolingUnitStatus}); if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) { $self->{output}->output_add(severity => $exit, short_msg => sprintf("Cooling unit '%s' status is '%s'", $result->{coolingUnitName}, $result->{coolingUnitStatus})); } } } 1;
wilfriedcomte/centreon-plugins
hardware/server/dell/idrac/snmp/mode/components/coolingunit.pm
Perl
apache-2.0
3,493
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Copyright [2016-2022] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =cut package Hive_exonerate_protein_file_conf; use strict; use warnings; use feature 'say'; use base ('Bio::EnsEMBL::Hive::PipeConfig::HiveGeneric_conf'); use Bio::EnsEMBL::ApiVersion qw/software_version/; sub default_options { my ($self) = @_; return { # inherit other stuff from the base class %{ $self->SUPER::default_options() }, ############################################################################ # # MOSTLY CHANGE # ############################################################################ 'pipeline_name' => '', 'pipe_db_name' => '', 'pipe_db_server' => '', 'reference_db_name' => '', # This should be a core db with DNA 'reference_db_server' => '', 'exonerate_output_db_name' => '', # This will be created for you automatically 'exonerate_output_db_server' => '', 'user_w' => '', 'password' => '', 'user_r' => 'ensro', 'port' => 3306, 'exonerate_pid' => '50', # Cut-off for percent id 'exonerate_cov' => '50', # Cut-off for coverage 'output_path' => '', 'protein_file' => '', 'genome_file' => '', 'repeat_masking_logic_names' => [], # e.g ['repeatmask_repbase_baboon','dust'] ############################################################################ # # MOSTLY CONSTANT # ############################################################################ 'create_type' => 'clone', 'num_tokens' => '10', 'user' => 'ensro', 'driver' => 'mysql', 'protein_table_name' => 'protein_sequences', 'exonerate_path' => '/software/ensembl/genebuild/usrlocalensemblbin/exonerate-0.9.0', 'exonerate_calculate_coverage_and_pid' => '1', 'default_mem' => '900', 'exonerate_mem' => '2900', 'exonerate_retry_mem' => '5900', 'pipeline_db' => { -host => $self->o('pipe_db_server'), -port => $self->o('port'), -user => $self->o('user_w'), -pass => $self->o('password'), -dbname => $self->o('pipe_db_name'), -driver => $self->o('driver'), }, 'reference_db' => { -dbname => $self->o('reference_db_name'), -host => $self->o('reference_db_server'), -port => $self->o('port'), -user => $self->o('user_r'), }, 'dna_db' => { -dbname => $self->o('reference_db_name'), -host => $self->o('reference_db_server'), -port => $self->o('port'), -user => $self->o('user_r'), }, 'exonerate_output_db' => { -dbname => $self->o('exonerate_output_db_name'), -host => $self->o('exonerate_output_db_server'), -port => $self->o('port'), -user => $self->o('user_w'), -pass => $self->o('password'), }, }; } sub pipeline_create_commands { my ($self) = @_; return [ # inheriting database and hive tables' creation @{$self->SUPER::pipeline_create_commands}, $self->db_cmd('CREATE TABLE '.$self->o('protein_table_name').' ('. 'accession varchar(50) NOT NULL,'. 'source varchar(50) NOT NULL,'. 'date varchar(50) NOT NULL,'. 'db_version varchar(50) NOT NULL,'. 'species varchar(50) NOT NULL,'. 'seq text NOT NULL,'. 'PRIMARY KEY (accession))'), ]; } sub hive_meta_table { my ($self) = @_; return { %{$self->SUPER::hive_meta_table}, # here we inherit anything from the base class 'hive_use_param_stack' => 1, # switch on the new param_stack mechanism }; } ## See diagram for pipeline structure sub pipeline_analyses { my ($self) = @_; return [ { -logic_name => 'create_exonerate_output_db', -module => 'Bio::EnsEMBL::Analysis::Hive::RunnableDB::HiveCreateDatabase', -parameters => { source_db => $self->o('reference_db'), target_db => $self->o('exonerate_output_db'), create_type => $self->o('create_type'), }, -rc_name => 'default', -input_ids => [{}], }, { -logic_name => 'load_protein_file', -module => 'Bio::EnsEMBL::Analysis::Hive::RunnableDB::HiveLoadProteins', -parameters => { protein_table_name => $self->o('protein_table_name'), }, -flow_into => { 1 => ['exonerate'], }, -input_ids => [{'protein_file' => $self->o('protein_file')}, ], -rc_name => 'default', }, { -logic_name => 'exonerate', -module => 'Bio::EnsEMBL::Analysis::Hive::RunnableDB::HiveExonerate2Genes', -rc_name => 'exonerate', -wait_for => ['create_exonerate_output_db'], -parameters => { iid_type => 'db_seq', query_table_name => 'protein_sequences', dna_db => $self->o('dna_db'), target_db => $self->o('exonerate_output_db'), logic_name => 'exonerate', module => 'HiveExonerate2Genes', config_settings => $self->get_config_settings('exonerate_protein','exonerate'), query_seq_dir => $self->o('output_path'), calculate_coverage_and_pid => $self->o('exonerate_calculate_coverage_and_pid'), }, -flow_into => { -1 => ['exonerate_retry'], -2 => ['failed_exonerate_proteins'], }, -batch_size => 100, -failed_job_tolerance => 5, }, { -logic_name => 'exonerate_retry', -module => 'Bio::EnsEMBL::Analysis::Hive::RunnableDB::HiveExonerate2Genes', -rc_name => 'exonerate', -parameters => { iid_type => 'db_seq', query_table_name => 'protein_sequences', dna_db => $self->o('dna_db'), target_db => $self->o('exonerate_output_db'), logic_name => 'exonerate', module => 'HiveExonerate2Genes', config_settings => $self->get_config_settings('exonerate_protein','exonerate'), query_seq_dir => $self->o('output_path'), calculate_coverage_and_pid => $self->o('exonerate_calculate_coverage_and_pid'), }, -flow_into => { -2 => ['failed_exonerate_proteins'], }, -batch_size => 100, -failed_job_tolerance => 100, -can_be_empty => 1, }, { -logic_name => 'failed_exonerate_proteins', -module => 'Bio::EnsEMBL::Hive::RunnableDB::Dummy', -parameters => {}, -rc_name => 'default', -can_be_empty => 1, -failed_job_tolerance => 100, }, ]; } sub pipeline_wide_parameters { my ($self) = @_; return { %{ $self->SUPER::pipeline_wide_parameters() }, # inherit other stuff from the base class }; } # override the default method, to force an automatic loading of the registry in all workers #sub beekeeper_extra_cmdline_options { # my $self = shift; # return "-reg_conf ".$self->o("registry"); #} sub resource_classes { my $self = shift; my $pipe_db_server = $self->default_options()->{'pipe_db_server'}; my $dna_db_server = $self->default_options()->{'reference_db_server'}; my $exonerate_output_db_server = $self->default_options()->{'exonerate_output_db_server'}; my $pipe_db_server_number; my $dna_db_server_number; my $exonerate_output_db_server_number; my $default_mem = $self->default_options()->{'default_mem'}; my $exonerate_mem = $self->default_options()->{'exonerate_mem'}; my $exonerate_retry_mem = $self->default_options()->{'exonerate_retry_mem'}; my $num_tokens = $self->default_options()->{'num_tokens'}; unless($pipe_db_server =~ /(\d+)$/) { die "Failed to parse the server number out of the pipeline db server name. This is needed for setting tokens\n". "pipe_db_server: ".$pipe_db_server; } $pipe_db_server_number = $1; unless($dna_db_server =~ /(\d+)$/) { die "Failed to parse the server number out of the pipeline db server name. This is needed for setting tokens\n". "dna_db_server: ".$dna_db_server; } $dna_db_server_number = $1; unless($exonerate_output_db_server =~ /(\d+)$/) { die "Failed to parse the server number out of the exonerate db server name. This is needed for setting tokens\n". "exonerate_output_db_server: ".$exonerate_output_db_server; } $exonerate_output_db_server_number = $1; unless($num_tokens) { die "num_tokens is uninitialised or zero. num_tokens needs to be present in default_options and not zero\n". "num_tokens: ".$num_tokens; } return { 'default' => { LSF => '-q normal -M'.$default_mem.' -R"select[mem>'.$default_mem.'] '. 'rusage[mem='.$default_mem.','. 'myens_build'.$pipe_db_server_number.'tok='.$num_tokens.']"' }, 'exonerate' => { LSF => '-q normal -W 120 -M'.$exonerate_mem.' -R"select[mem>'.$exonerate_mem.'] '. 'rusage[mem='.$exonerate_mem.','. 'myens_build'.$exonerate_output_db_server_number.'tok='.$num_tokens.','. 'myens_build'.$dna_db_server_number.'tok='.$num_tokens.','. 'myens_build'.$pipe_db_server_number.'tok='.$num_tokens.']"' }, 'exonerate_retry' => { LSF => '-q normal -W 120 -M'.$exonerate_retry_mem.' -R"select[mem>'.$exonerate_retry_mem.'] '. 'rusage[mem='.$exonerate_retry_mem.','. 'myens_build'.$exonerate_output_db_server_number.'tok='.$num_tokens.','. 'myens_build'.$dna_db_server_number.'tok='.$num_tokens.','. 'myens_build'.$pipe_db_server_number.'tok='.$num_tokens.']"' }, } } sub get_config_settings { # Shift in the group name (a hash that has a collection of logic name hashes and a default hash) # Shift in the logic name of the specific analysis my $self = shift; my $config_group = shift; my $config_logic_name = shift; # And additional hash keys will be stored in here my @additional_configs = @_; # Return a ref to the master hash for the group using the group name my $config_group_hash = $self->master_config_settings($config_group); unless(defined($config_group_hash)) { die "You have asked for a group name in master_config_settings that doesn't exist. Group name:\n".$config_group; } # Final hash is the hash reference that gets returned. It is important to note that the keys added have # priority based on the call to this subroutine, with priority from left to right. Keys assigned to # $config_logic_name will have most priority, then keys in any additional hashes, then keys from the # default hash. A default hash key will never override a $config_logic_name key my $final_hash; # Add keys from the logic name hash my $config_logic_name_hash = $config_group_hash->{$config_logic_name}; unless(defined($config_logic_name_hash)) { die "You have asked for a logic name hash that doesn't exist in the group you specified.\n". "Group name:\n".$config_group."\nLogic name:\n".$config_logic_name; } $final_hash = $self->add_keys($config_logic_name_hash,$final_hash); # Add keys from any additional hashes passed in, keys that are already present will not be overriden foreach my $additional_hash (@additional_configs) { my $config_additional_hash = $config_group_hash->{$additional_hash}; $final_hash = $self->add_keys($config_additional_hash,$final_hash); } # Default is always loaded and has the lowest key value priority my $config_default_hash = $config_group_hash->{'Default'}; $final_hash = $self->add_keys($config_default_hash,$final_hash); return($final_hash); } sub add_keys { my ($self,$hash_to_add,$final_hash) = @_; foreach my $key (keys(%$hash_to_add)) { unless(exists($final_hash->{$key})) { $final_hash->{$key} = $hash_to_add->{$key}; } } return($final_hash); } sub master_config_settings { my ($self,$config_group) = @_; my $master_config_settings = { exonerate_protein => { Default => { IIDREGEXP => '(\d+):(\d+)', OPTIONS => '--model protein2genome --forwardcoordinates FALSE --softmasktarget TRUE --exhaustive FALSE --bestn 1', COVERAGE_BY_ALIGNED => 0, QUERYTYPE => 'protein', GENOMICSEQS => $self->o('genome_file'), PROGRAM => $self->o('exonerate_path'), SOFT_MASKED_REPEATS => $self->o('repeat_masking_logic_names'), }, exonerate => { FILTER => { OBJECT => 'Bio::EnsEMBL::Analysis::Tools::ExonerateTranscriptFilter', PARAMETERS => { -coverage => $self->o('exonerate_cov'), -percent_id => $self->o('exonerate_pid'), -best_in_genome => 1, -reject_processed_pseudos => 1, }, }, }, }, }; return($master_config_settings->{$config_group}); } 1;
Ensembl/ensembl-analysis
modules/Bio/EnsEMBL/Analysis/Hive/Config/HiveGeneBuilding/Hive_exonerate_protein_file_conf.pm
Perl
apache-2.0
15,525
# # Copyright 2018 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package network::digi::sarian::snmp::mode::gprs; use base qw(centreon::plugins::templates::counter); use strict; use warnings; my $instance_mode; sub custom_status_threshold_output { my ($self, %options) = @_; my $status = 'ok'; my $message; eval { local $SIG{__WARN__} = sub { $message = $_[0]; }; local $SIG{__DIE__} = sub { $message = $_[0]; }; if (defined($instance_mode->{option_results}->{critical_status}) && $instance_mode->{option_results}->{critical_status} ne '' && eval "$instance_mode->{option_results}->{critical_status}") { $status = 'critical'; } elsif (defined($instance_mode->{option_results}->{warning_status}) && $instance_mode->{option_results}->{warning_status} ne '' && eval "$instance_mode->{option_results}->{warning_status}") { $status = 'warning'; } }; if (defined($message)) { $self->{output}->output_add(long_msg => 'filter status issue: ' . $message); } return $status; } sub custom_status_output { my ($self, %options) = @_; my $msg; $msg = 'Attachement : ' . $self->{result_values}->{attachement}; $msg .= ', Registration : ' . $self->{result_values}->{registered}; return $msg; } sub custom_status_calc { my ($self, %options) = @_; $self->{result_values}->{registered} = $options{new_datas}->{$self->{instance} . '_registered'}; $self->{result_values}->{attachement} = $options{new_datas}->{$self->{instance} . '_attachement'}; return 0; } sub custom_tech_threshold_output { my ($self, %options) = @_; my $status = 'ok'; my $message; eval { local $SIG{__WARN__} = sub { $message = $_[0]; }; local $SIG{__DIE__} = sub { $message = $_[0]; }; if (defined($instance_mode->{option_results}->{critical_technology}) && $instance_mode->{option_results}->{critical_technology} ne '' && eval "$instance_mode->{option_results}->{critical_technology}") { $status = 'critical'; } elsif (defined($instance_mode->{option_results}->{warning_technology}) && $instance_mode->{option_results}->{warning_technology} ne '' && eval "$instance_mode->{option_results}->{warning_technology}") { $status = 'warning'; } }; if (defined($message)) { $self->{output}->output_add(long_msg => 'filter status issue: ' . $message); } return $status; } sub custom_tech_output { my ($self, %options) = @_; my $msg; $msg = 'Technology : ' . $self->{result_values}->{technology}; return $msg; } sub custom_tech_calc { my ($self, %options) = @_; $self->{result_values}->{technology} = $options{new_datas}->{$self->{instance} . '_technology'}; return 0; } sub set_counters { my ($self, %options) = @_; $self->{maps_counters_type} = [ { name => 'gprs', type => 0 }, ]; $self->{maps_counters}->{gprs} = [ { label => 'signal', set => { key_values => [ { name => 'signal' } ], output_template => 'Signal : %d dBm', perfdatas => [ { label => 'signal_strenght', value => 'signal_absolute', template => '%s', unit => 'dBm' }, ], } }, { label => 'status', threshold => 0, set => { key_values => [ { name => 'registered' }, { name => 'attachement' } ], closure_custom_calc => $self->can('custom_status_calc'), closure_custom_output => $self->can('custom_status_output'), closure_custom_perfdata => sub { return 0; }, closure_custom_threshold_check => $self->can('custom_status_threshold_output'), } }, { label => 'technology', threshold => 0, set => { key_values => [ { name => 'technology' } ], closure_custom_calc => $self->can('custom_tech_calc'), closure_custom_output => $self->can('custom_tech_output'), closure_custom_perfdata => sub { return 0; }, closure_custom_threshold_check => $self->can('custom_tech_threshold_output'), } }, ]; } sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; $self->{version} = '1.0'; $options{options}->add_options(arguments => { "warning-status:s" => { name => 'warning_status', default => '' }, "critical-status:s" => { name => 'critical_status', default => '%{attachement} eq "notAttached" or %{registered} !~ /registeredHostNetwork|registeredRoaming/' }, "warning-technology:s" => { name => 'warning_technology', default => '' }, "critical-technology:s" => { name => 'critical_technology', default => '%{technology} !~ /2G|3G|4G/' }, }); return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::check_options(%options); $instance_mode = $self; $self->change_macros(); } sub change_macros { my ($self, %options) = @_; foreach (('warning_status', 'critical_status', 'warning_technology', 'critical_technology' )) { if (defined($self->{option_results}->{$_})) { $self->{option_results}->{$_} =~ s/%\{(.*?)\}/\$self->{result_values}->{$1}/g; } } } my %map_gprs_registration = ( 0 => 'notRegisteredNotSearching', 1 => 'registeredHostNetwork', 2 => 'notRegisteredSearching', 3 => 'registrationDenied', 4 => 'unknown', 5 => 'registeredRoaming', 6 => 'unrecognised', ); my %map_gprs_attachement = ( 0 => 'notAtached', 1 => 'attached', ); my %map_gprs_technology = ( 1 => 'unknown', 2 => 'GPRS(2G)', 3 => 'EDGE(2G)', 4 => 'UMTS(3G)', 5 => 'HSDPA(3G)', 6 => 'HSUPA(3G)', 7 => 'DC-HSPA+(3G)', 8 => 'LTE(4G)', ); my $oid_gprsSignalStrength = '.1.3.6.1.4.1.16378.10000.2.1.0'; my $oid_gprsRegistered = '.1.3.6.1.4.1.16378.10000.2.2.0'; my $oid_gprsAttached = '.1.3.6.1.4.1.16378.10000.2.3.0'; my $oid_gprsNetworkTechnology = '.1.3.6.1.4.1.16378.10000.2.7.0'; sub manage_selection { my ($self, %options) = @_; $self->{gprs} = {}; $self->{results} = $options{snmp}->get_leef(oids => [ $oid_gprsSignalStrength, $oid_gprsRegistered, $oid_gprsAttached, $oid_gprsNetworkTechnology ], nothing_quit => 1); $self->{gprs} = { signal => $self->{results}->{$oid_gprsSignalStrength}, registered => $map_gprs_registration{$self->{results}->{$oid_gprsRegistered}}, attachement => $map_gprs_attachement{$self->{results}->{$oid_gprsAttached}}, technology => $map_gprs_technology{$self->{results}->{$oid_gprsNetworkTechnology}}, }; } 1; __END__ =head1 MODE Check GPRS status. =over 8 =item B<--filter-counters> Only display some counters (regexp can be used). Example: --filter-counters='signal|technology' =item B<--warning-status> Set warning threshold for status. Can used special variables like: %{registered}, %{attachement} =item B<--critical-status> Set critical threshold for status (Default: '%{attachement} eq "attached" and %{registered} !~ /registeredHostNetwork|registeredRoaming/' Can used special variables like: %{registered}, %{attachement} =item B<--warning-technology> Set warning threshold for technology. Use special variables %{technology}. =item B<--critical-technology> Set critical threshold for technology (Default: '%{technology} !~ /2G|3G|4G/' Use special variables %{technology}. =item B<--warning-signal> Threshold warning for signal strength. =item B<--critical-signal> Threshold critical for signal strength. =back =cut
wilfriedcomte/centreon-plugins
network/digi/sarian/snmp/mode/gprs.pm
Perl
apache-2.0
8,847
package Paws::CloudSearchDomain::Hits; use Moose; has Cursor => (is => 'ro', isa => 'Str', request_name => 'cursor', traits => ['NameInRequest']); has Found => (is => 'ro', isa => 'Int', request_name => 'found', traits => ['NameInRequest']); has Hit => (is => 'ro', isa => 'ArrayRef[Paws::CloudSearchDomain::Hit]', request_name => 'hit', traits => ['NameInRequest']); has Start => (is => 'ro', isa => 'Int', request_name => 'start', traits => ['NameInRequest']); 1; ### main pod documentation begin ### =head1 NAME Paws::CloudSearchDomain::Hits =head1 USAGE This class represents one of two things: =head3 Arguments in a call to a service Use the attributes of this class as arguments to methods. You shouldn't make instances of this class. Each attribute should be used as a named argument in the calls that expect this type of object. As an example, if Att1 is expected to be a Paws::CloudSearchDomain::Hits object: $service_obj->Method(Att1 => { Cursor => $value, ..., Start => $value }); =head3 Results returned from an API call Use accessors for each attribute. If Att1 is expected to be an Paws::CloudSearchDomain::Hits object: $result = $service_obj->Method(...); $result->Att1->Cursor =head1 DESCRIPTION The collection of documents that match the search request. =head1 ATTRIBUTES =head2 Cursor => Str A cursor that can be used to retrieve the next set of matching documents when you want to page through a large result set. =head2 Found => Int The total number of documents that match the search request. =head2 Hit => ArrayRef[L<Paws::CloudSearchDomain::Hit>] A document that matches the search request. =head2 Start => Int The index of the first matching document. =head1 SEE ALSO This class forms part of L<Paws>, describing an object used in L<Paws::CloudSearchDomain> =head1 BUGS and CONTRIBUTIONS The source code is located here: https://github.com/pplu/aws-sdk-perl Please report bugs to: https://github.com/pplu/aws-sdk-perl/issues =cut
ioanrogers/aws-sdk-perl
auto-lib/Paws/CloudSearchDomain/Hits.pm
Perl
apache-2.0
2,016
package Poller; use strict; use LWP::Simple qw(RC_OK RC_NOT_MODIFIED); sub new { my $proto = shift; my $class = ref($proto) || $proto; my $self = {}; %{$self->{params}} = @_; bless ($self, $class); return $self; } sub name { my $self = shift; ($self =~ m/Poller::(.*?)=/)[0]; } sub data_file { my $self = shift; $self->{data_file} = $_[0] if $_[0]; $self->{data_file} ? $self->{data_file} : "data/" . $self->name . ".data"; } sub lb_list { my $self = shift; $self->{lb_list} = $_[0] if $_[0] && ref $_[0] eq "ARRAY"; $self->{lb_list} ? @{$self->{lb_list}} : (); } sub mirror_url { my ($self, $url) = @_; my $file = $self->data_file; my $mirror_rv = LWP::Simple::mirror($url, $file); if ($mirror_rv == RC_NOT_MODIFIED) { return 0; } unless ($mirror_rv == RC_OK) { print "poller could not mirror datafile from $url to $file: $mirror_rv\n"; return 0; } 1; } 1;
abh/pgeodns
poller/perl/Poller.pm
Perl
apache-2.0
920
#!/usr/bin/env perl # Integration tests for build command line tool #*************************************************************************** # Copyright 2014-2017, mettatw <mettatw@users.noreply.github.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #*************************************************************************** use warnings; use strict; use v5.14; use FindBin qw($Bin); use lib "$Bin/local/lib/perl5"; use lib "$Bin/../local/lib/perl5"; use lib "$Bin/../lib"; use Test2::V0; use Test2::Tools::Spec ':ALL'; spec_defaults case => (iso => 1, async => 1); use File::Slurp; use POSIX qw(strftime); use IPC::Cmd qw( run_forked ); $ENV{'PATH'} = "$Bin/../bin:$ENV{'PATH'}"; use lib "$Bin"; use CommonBuildTest; describe 'Run the build generator and check results' => sub { before_all 'Build test repo' => sub { prepareBuildDir("$Bin/build", "$Bin/data"); }; before_case 'Fallback options' => sub { my $self = shift; $self->{'.param'} = ''; $self->{'.tofail'} = 0; $self->{'.ans'} = 'ATemplate'; }; case 'simple source script' => sub { my $self = shift; $self->{'.input'} = 'shellframe/source.sh'; }; case 'simple shell script' => sub { my $self = shift; $self->{'.input'} = 'shellframe/shell.sh'; }; case 'exported shell script' => sub { my $self = shift; $self->{'.input'} = 'shellframe/hash.sh'; }; case 'variable source' => sub { my $self = shift; $self->{'.input'} = 'shellframe/var.sh'; }; case 'double tag only appear once' => sub { my $self = shift; $self->{'.input'} = 'shellframe/doubletag.sh'; }; case 'misc thing: auto external build do work' => sub { my $self = shift; $self->{'.input'} = 'shellframe/meta.sh'; $self->{'.ans'} = strftime("%Y%m%d", localtime); }; case 'Options (without shell-begin)' => sub { my $self = shift; $self->{'.input'} = 'shellframe/optionsonly.sh'; $self->{'.ans'} = "325\nquote\n1\n1\n326\n0\nvalue\n1"; }; case 'Scalar options' => sub { my $self = shift; $self->{'.input'} = 'shellframe/options.sh'; $self->{'.ans'} = "5566\n33.44"; }; case 'Scalar options: specify from command line' => sub { my $self = shift; $self->{'.param'} = 'optionnumber=3344'; $self->{'.input'} = 'shellframe/options.sh'; $self->{'.ans'} = "3344\n33.44"; }; case 'Scalar options: required not met' => sub { my $self = shift; $self->{'.param'} = 'optionnumber='; $self->{'.input'} = 'shellframe/options.sh'; $self->{'.tofail'} = 1; }; case 'Scalar options: mismatched type' => sub { my $self = shift; $self->{'.param'} = 'optionfloat=ABCD'; $self->{'.input'} = 'shellframe/options.sh'; $self->{'.tofail'} = 1; }; case 'Scalar options: mismatched type 2' => sub { my $self = shift; $self->{'.param'} = 'optionnumber=3.14'; $self->{'.input'} = 'shellframe/options.sh'; $self->{'.tofail'} = 1; }; case 'Array options: specify from command line' => sub { my $self = shift; $self->{'.param'} = 'optionnumber=11 --optionnumber=22'; $self->{'.input'} = 'shellframe/array.sh'; $self->{'.ans'} = "11 22"; }; case 'Array options: wrong type' => sub { my $self = shift; $self->{'.param'} = 'optionnumber=ABCD'; $self->{'.input'} = 'shellframe/array.sh'; $self->{'.tofail'} = 1; }; it 'Run fine and answer correct' => sub { my $self = shift; my $stats = run_forked(qq( cd $Bin/build && run/$self->{'.input'} $self->{'.param'} )); if ($self->{'.tofail'} == 1) { isnt($stats->{'exit_code'}, 0, $stats->{'stderr'}); } else { my $output = $stats->{'stdout'}; chomp($output); is($stats->{'exit_code'}, 0, $stats->{'stderr'}); is($output, $self->{'.ans'}, 'correct answer'); } }; # end test Run ok }; # end test fix Run the build generator and check results done_testing;
mettatw/ubiquitous-octo-spork
test/int-shellframe.pl
Perl
apache-2.0
4,439
package Mojo::Webqq::Plugin::GroupManage; use strict; use List::Util qw(first); our $PRIORITY = 100; use POSIX (); sub do_speak_limit{ my($client,$data,$speak_counter,$msg) = @_; $data->{is_new_group_notice} //= 1; $data->{is_new_group_member_notice} //= 1; $data->{is_lose_group_member_notice} //= 1; $data->{is_group_member_property_change_notice} //= 0; my $gid = $msg->group->id; my $sender_id = $msg->sender->id; my $warn_limit = $data->{speak_limit}{warn_limit}; my $warn_message = $data->{speak_limit}{warn_message} || '@%s 警告, 您发言过于频繁,可能会被禁言或踢出本群'; my $shutup_limit = $data->{speak_limit}{shutup_limit}; my $shutup_time = $data->{speak_limit}{shutup_time} || 600; my $kick_limit = $data->{speak_limit}{kick_limit}; my $count = $speak_counter->check($gid . "|" . $sender_id,$msg->time); if(defined $kick_limit and $count >= $kick_limit){ $msg->group->kick_group_member($msg->sender); $speak_counter->clear($gid . "|" . $sender_id); } elsif(defined $shutup_limit and $count >= $shutup_limit){ $msg->group->shutup_group_member($shutup_time,$msg->sender); $speak_counter->clear($gid . "|" . $sender_id); } elsif(defined $warn_limit and $count >= $warn_limit){ $msg->reply(sprintf $warn_message,$msg->sender->displayname); } } sub do_pic_limit{ my($client,$data,$pic_counter,$msg) = @_; my $gid = $msg->group->id; my $sender_id = $msg->sender->id; return if not first {$_->{type} eq 'cface'} @{$msg->raw_content}; my $warn_limit = $data->{pic_limit}{warn_limit}; my $warn_message = $data->{pic_limit}{warn_message} || '@%s 警告, 您发图过多,可能会被禁言或踢出本群'; my $shutup_limit = $data->{pic_limit}{shutup_limit}; my $shutup_time = $data->{pic_limit}{shutup_time} || 600; my $kick_limit = $data->{pic_limit}{kick_limit}; for(@{$msg->raw_content}){ if($_->{type} eq 'cface'){ $pic_counter->count($gid . "|" . $sender_id,$msg->time); } } my $count = $pic_counter->look($gid . "|" . $sender_id); if(defined $kick_limit and $count >= $kick_limit){ $msg->sender->group->kick_group_member($msg->sender); $pic_counter->clear($gid . "|" . $sender_id); } elsif(defined $shutup_limit and $count >= $shutup_limit){ $msg->sender->group->shutup_group_member($shutup_time,$msg->sender); $pic_counter->clear($gid . "|" . $sender_id); } elsif(defined $warn_limit and $count >= $warn_limit){ $msg->reply(sprintf $warn_message,$msg->sender->displayname); } } sub do_keyword_limit { my($client,$data,$keyword_counter,$msg) = @_; my $gid = $msg->group->id; my $sender_id = $msg->sender->id; my @keywords = ref $data->{keyword_limit}{keyword} eq "ARRAY"?@{$data->{keyword_limit}{keyword}}:(); return if @keywords == 0; return if not first {$msg->content =~/\Q$_\E/} @keywords; my $warn_limit = $data->{keyword_limit}{warn_limit}; my $warn_message = $data->{keyword_limit}{warn_message} || '@%s 警告, 您发言包含限制内容,可能会被禁言或踢出本群'; my $shutup_limit = $data->{keyword_limit}{shutup_limit}; my $shutup_time = $data->{keyword_limit}{shutup_time} || 600; my $kick_limit = $data->{keyword_limit}{kick_limit}; my $count = $keyword_counter->check($gid . "|" . $sender_id,$msg->time); if(defined $kick_limit and $count >= $kick_limit){ $msg->sender->group->kick_group_member($msg->sender); $keyword_counter->clear($gid . "|" . $sender_id); } elsif(defined $shutup_limit and $count >= $shutup_limit){ $msg->sender->group->shutup_group_member($shutup_time,$msg->sender); $keyword_counter->clear($gid . "|" . $sender_id); } elsif(defined $warn_limit and $count >= $warn_limit){ $msg->reply(sprintf $warn_message,$msg->sender->displayname); } } sub call { my $client = shift; my $data = shift; my $speak_counter = $client->new_counter(id=>'GroupManage_speek',period=>$data->{speak_limit}{period} || 600); my $pic_counter = $client->new_counter(id=>'GroupManage_pic',period=>$data->{pic_limit}{period} || 600); my $keyword_counter = $client->new_counter(id=>'GroupManage_keyword',period=>$data->{keyword_limit}{period} || 600); $client->on(login=>sub{$speak_counter->reset();$pic_counter->reset();$keyword_counter->reset()}); $client->on( receive_message => sub { my($client,$msg) = @_; return if $msg->type ne "group_message"; return if $data->{is_need_at} and $msg->type eq "group_message" and !$msg->is_at; return if ref $data->{ban_group} eq "ARRAY" and first {$_=~/^\d+$/?$msg->group->uid eq $_:$msg->group->name eq $_} @{$data->{ban_group}}; return if ref $data->{allow_group} eq "ARRAY" and !first {$_=~/^\d+$/?$msg->group->uid eq $_:$msg->group->name eq $_} @{$data->{allow_group}}; #说话频率限制 do_speak_limit($client,$data,$speak_counter,$msg); #发图数量限制 do_pic_limit($client,$data,$pic_counter,$msg); #关键字限制 do_keyword_limit($client,$data,$keyword_counter,$msg) }, new_group => sub { return if not $data->{is_new_group_notice}; my $group = $_[1]; return if ref $data->{ban_group} eq "ARRAY" and first {$_=~/^\d+$/?$group->uid eq $_:$group->name eq $_} @{$data->{ban_group}}; return if ref $data->{allow_group} eq "ARRAY" and !first {$_=~/^\d+$/?$group->uid eq $_:$group->name eq $_} @{$data->{allow_group}}; $group->send($data->{new_group} || "大家好,初来咋到,请多关照"); }, #lose_group => sub { }, new_group_member => sub { return if not $data->{is_new_group_member_notice}; my $member = $_[1]; my $group = $member->group; return if ref $data->{ban_group} eq "ARRAY" and first {$_=~/^\d+$/?$group->uid eq $_:$group->name eq $_} @{$data->{ban_group}}; return if ref $data->{allow_group} eq "ARRAY" and !first {$_=~/^\d+$/?$group->uid eq $_:$group->name eq $_} @{$data->{allow_group}}; my $displayname = $member->displayname; return if $displayname eq "昵称未知"; $group->send( sprintf($data->{new_group_member} || '欢迎新成员 @%s 入群[鼓掌][鼓掌][鼓掌]',$displayname) ); }, lose_group_member => sub { return if not $data->{is_lose_group_member_notice}; my $member = $_[1]; my $group = $member->group; return if ref $data->{ban_group} eq "ARRAY" and first {$_=~/^\d+$/?$group->uid eq $_:$group->name eq $_} @{$data->{ban_group}}; return if ref $data->{allow_group} eq "ARRAY" and !first {$_=~/^\d+$/?$group->uid eq $_:$group->name eq $_} @{$data->{allow_group}}; my $displayname = $member->displayname; return if $displayname eq "昵称未知"; $group->send( sprintf($data->{lose_group_member} || '很遗憾 @%s 离开了本群[流泪][流泪][流泪]',$displayname) ); }, #new_discuss_member => sub { }, #lose_discuss_member => sub { }, #new_friend => sub { }, #lose_friend => sub { }, group_member_property_change => sub { return if not $data->{is_group_member_property_change_notice}; my($client,$member,$property,$old,$new)=@_; my $group = $member->group; return if ref $data->{ban_group} eq "ARRAY" and first {$_=~/^\d+$/?$group->uid eq $_:$group->name eq $_} @{$data->{ban_group}}; return if ref $data->{allow_group} eq "ARRAY" and !first {$_=~/^\d+$/?$group->uid eq $_:$group->name eq $_} @{$data->{allow_group}}; return if $property ne "card"; return if not defined($new); return if not defined($old); $group->send('@' . (defined($old)?$old:$member->name) . " 修改群名片为: $new"); } ); } 1;
sjdy521/Mojo-Webqq
lib/Mojo/Webqq/Plugin/GroupManage.pm
Perl
bsd-2-clause
8,307
#!/usr/bin/perl use strict; if( @ARGV < 1 ){ print "Need 1 Input: <directory_of_cloud_user_logs>\n"; exit(1); }; my $data_dir = shift @ARGV; my $data_name = "actual_cloud_display.log"; my $new_data_name = "accumul_actual_cloud_display.log"; my $input_file = $data_dir . "/" . $data_name; open(DATA, "< $input_file") or die $!; my $ts; my $acct; my $user; my $password; my $running_instances = 0; my $volumes = 0; my $snapshots = 0; my $security_groups = 0; my $keypairs = 0; my $ip_addresses = 0; my $is_populate_run = 0; my $output_file = $data_dir . "/" . $new_data_name; open(ACCUMUL, "> $output_file") or die $!; my $line; while($line=<DATA>){ chomp($line); # print $line . "\n"; if( $line =~ /^(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/){ if( $is_populate_run == 0 ){ $is_populate_run = 1; $ts = $1; $acct = $2; $user = $3; $password = $4; $running_instances += $5; $volumes += $6; $snapshots += $7; $security_groups += $8 - 1; $keypairs += $9; $ip_addresses += $10; print ACCUMUL "$ts\t$acct\t$user\t$password\t$running_instances\t$volumes\t$snapshots\t$security_groups\t$keypairs\t$ip_addresses\n"; }else{ $is_populate_run = 0; }; }; }; close(DATA); close(ACCUMUL); exit(0); 1;
eucalyptus/euca-monkey
cloud_user_workload_generator/plot_cloud_user_data/create_accumul_actual_cloud_user_data.pl
Perl
bsd-2-clause
1,305
package TCDB:PDB::CutHelixBundle; use warnings; no warnings; #To remove harmeless warnings from overriding accessors use strict; use Data::Dumper; use R2::PDB::Parser; use Class::Struct; #========================================================================== # The purpose of this class is cut PDB files in subsets of structures # containing a predefined number of contiguous alpha-helices. For example, # if there are 5 helices in the structre and we want sets of 3-helix bundles # per pdb files, the script will generate 3 files with the helices: # (1,2,3), (2,3,4) and (3,4,5). # # NOTE: # Mapping original ATOM positions to a position relative to SEQRES # (to easily map atoms to TMS positions) will not always work # because in some structures the ATOM sequence is not identical # to the SEQRES sequence (e.g. 4PGW). For this reason I decided # to use the ATOM sequence to run hmmtop. # # ------- # # # GENERAL GUIDE FOR USAGE: # # Load class: # use R2::PDB::CutHelixBundle; # # # Constructor: # # my $myObj = R2::PDB::CutHelixBundle->new( # pdb_to_cut => $myPDBfile, # resolution_cutoff => $myThreshold, # helix_bundle_size => $myHelixBundle, # pdb => {infile => $myPDBfile, min_helix_size => $myHelixSize} # ); # # # # Get help about this class: # # $myObj->help; # # # # Initiallizing object through constructor: # # my $myObj = new R2::PDBparser(infile => '/path/to/pdb/file'); # # # Initializing object through accessors: # # my $myObj = new R2::PDBparser(); # $myObj->infile('/path/to/pdb/file'); # # # # Once object is initialized parse the PDB file as: # # $myObj->parse_pdb(); # # # # ------- # Date created: 11/13/2015 # Programmer: Arturo Medrano # Institution: UCSD, WLU #========================================================================== struct ("R2::PDB::CutHelixBundle" => { 'pdb_to_cut' => '$', #Input PDB file to cut 'outdir' => '$', #Directory where cut structures will be placed. 'helix_bundle_size' => '$', #Cut the helices in budles of this number 'helix_bundle_tails' => '$', #How many residues to leave before an after the helx bundle. 'debug' => '$', #Variable that facilites printing debug messages 'pdb' => 'R2::PDB::Parser' #The PDB parser object } ); ########################################################################### ##### Override accessors that require default values ##### ##### (This generates harmless warings, make sure to turn the off) ##### ########################################################################### #========================================================================== #Assign default output dir if not provided by the user. sub outdir { my ($self, $dir) = @_; my $default_dir = "./helix_bundles"; if ( $dir ) { system "mkdir -p $dir" unless (-d $dir); $self->{'R2::PDB::CutHelixBundle::outdir'} = $dir; } unless ($self->{'R2::PDB::CutHelixBundle::outdir'}) { system "mkdir $default_dir" unless (-d $default_dir); $self->{'R2::PDB::CutHelixBundle::outdir'} = $default_dir; } return $self->{'R2::PDB::CutHelixBundle::outdir'}; } #========================================================================== #Assign default helix bundle size to cut if not provided by the user. sub helix_bundle_size { my ($self, $size) = @_; my $default_size = 3; if ($size) { #validate unless ( $size > 1 ) { die "Error: helix_bundle_size only takes integer values greater than 1\n"; } $self->{'R2::PDB::CutHelixBundle::helix_bundle_size'} = $size; } unless ($self->{'R2::PDB::CutHelixBundle::helix_bundle_size'}) { $self->{'R2::PDB::CutHelixBundle::helix_bundle_size'} = $default_size; } return $self->{'R2::PDB::CutHelixBundle::helix_bundle_size'}; } #========================================================================== #Assign default tail size for cutting helix bundles if not privided by #he user. sub helix_bundle_tails { my ($self, $tail_size) = @_; my $default_tail_size = 1; if ($tail_size) { #Validate unless ($tail_size =~ /^\d+$/ && $tail_size > 0) { die "Error: helix_bundle_tails only takes integer values greater than zero.\n"; } $self->{'R2::PDB::CutHelixBundle::helix_bundle_tails'} = $tail_size; } unless ($self->{'R2::PDB::CutHelixBundle::helix_bundle_tails'}){ $self->{'R2::PDB::CutHelixBundle::helix_bundle_tails'} = $default_tail_size; } return $self->{'R2::PDB::CutHelixBundle::helix_bundle_tails'}; } ########################################################################### ##### The methods in this class ##### ########################################################################### #========================================================================== # # sub cut_helix_bundles { my ($self, $chain) = @_; my $pdb_id = $self->pdb->id . "_$chain"; #Determine whether the structure has helices annotated die "Error: No helices in structure $pdb_id\n" unless (%{ $self->pdb->helix }); #Structures with no resolutions data have a 100 value assigned in the parser # return 3 if ($self->pdb->resolution > $self->resolution_cutoff); #There must be at least the number of helices that we want to cut unless (scalar keys %{ $self->pdb->stride->{$chain} } >= $self->helix_bundle_size) { print "Need at least ", $self->helix_bundle_size, " helices in strucure $pdb_id to make the cut\n"; return; } #Identify the index of the first helix in the last bundle my @helices = sort {$a <=> $b} keys %{ $self->pdb->stride->{$chain} }; my $first_helix_idx = $helices[0]; my $last_helix_idx = $helices[$#helices] - $self->helix_bundle_size + 1; #Cut helices according to the helix-bundle size provided by the user for (my $i = $first_helix_idx; $i <= $last_helix_idx ; $i++) { #Get the first and last helices in the bundle my $first_helix = $self->pdb->stride->{$chain}->{$i}; my $last_helix = $self->pdb->stride->{$chain}->{$i + $self->helix_bundle_size - 1}; #Now get the first and last residues in the helix bundle (left and right tails) my $first_res = $first_helix->[1]; my $last_res = $last_helix->[3]; #the left tail my ($lTail, $rTail) = undef; if ($first_res - $self->helix_bundle_tails < 1) { $lTail = 1; } else { $lTail = $first_res - $self->helix_bundle_tails; } #The right tail if ($last_res + $self->helix_bundle_tails > scalar keys %{ $self->pdb->atom_seq1->{$chain} }) { $rTail = scalar keys %{ $self->pdb->atom_seq1->{$chain} }; } else { $rTail = $last_res + $self->helix_bundle_tails; } # print Data::Dumper->Dump([$first_helix, $last_helix, $first_res, $last_res],[qw(*first *last *first_res *last_res)]); # <STDIN>; #Create the PDB file with the cut helices my @helices_in_this_bundle = ($i .. $i + $self->helix_bundle_size - 1); my $helices_str = join("_", @helices_in_this_bundle); my $hbundle_name = "${pdb_id}_h$helices_str"; $self->generate_helix_bundle_pdb_file($chain, $hbundle_name, \@helices_in_this_bundle, $lTail, $rTail); #print "Helix bundle PDB file generated: $hbundle_name\n"; } return 1; } #========================================================================== #Given the cordinates of the first and last amino acid in a helix bundle, #generate a PDB file with the corresponding atom coordinates. sub generate_helix_bundle_pdb_file { my ($self, $chain, $bundle_name, $bundle_helices, $firstRes, $lastRes) = @_; #The output directory my $outdir = $self->outdir; #The output file name my $pdb_file = "$outdir/${bundle_name}.pdb"; #Do generate bundle file if it already exists return if (-f $pdb_file); open (my $fhandle, ">", $pdb_file) || die $!; #Print the header print $fhandle $self->pdb->header, "\n"; #Resolution line if ($self->pdb->resolution_line) { print $fhandle $self->pdb->resolution_line, "\n"; } #The DBREF section to extract SwissProt IDs print $fhandle join("\n", @{ $self->pdb->dbref_lines->{$chain} }), "\n"; #The MODRES section if (exists $self->pdb->modres->{$chain} && @{ $self->pdb->modres->{$chain} }) { print $fhandle join ("\n", @{ $self->pdb->modres->{$chain} }), "\n"; } #Print the helix section foreach my $helix (@{ $self->pdb->helix->{$chain} }) { print $fhandle "$helix\n"; } #Print the atoms of the bundle foreach my $res_num ($firstRes .. $lastRes) { foreach my $atom (@{ $self->pdb->atom->{$chain}->{$res_num} }) { print $fhandle "$atom\n"; } } #The CONNECT section if it exists if (@{ $self->pdb->connect }) { print $fhandle join("\n", @{ $self->pdb->connect }), "\n"; } #The MASTER line if it exists print $fhandle $self->pdb->master, "\n" if ($self->pdb->master); print $fhandle "END\n"; close $fhandle; } #========================================================================== #Get the index of the first helix that overlaps the first TMS sub get_idx_of_first_helix { my ($self, $chain) = @_; my $idx_last_helix = $#{ $self->helix_corrected->{$chain} }; HELIX:foreach my $idx ( 0 .. $idx_last_helix ) { my $helix = $self->helix_corrected->{$chain}->[$idx]; my $lpos = $self->trim(substr($helix, 21, 4)); #chars 22-26 my $rpos = $self->trim(substr($helix, 33, 4)); #chars 34-37 #return index of first helix with overlap if ( $self->is_there_overlap([$lpos, $rpos], $self->hmmtop->{$chain}->[0]) ) { return $idx; } } #no overlap found return undef; } #========================================================================== #Determine whether there 2 sets of amino acid positions overlap sub is_there_overlap { my ($self, $coords1, $coords2) = @_; my ($l1, $r1) = undef; my ($l2, $r2) = undef; #assign l1 and r1 to the left most set of coordinates if ($coords1->[0] <= $coords2->[0]) { ($l1, $r1) = @$coords1; ($l2, $r2) = @$coords2; } else { ($l2, $r2) = @$coords1; ($l1, $r1) = @$coords2; } #coordinates must be grater than zero die "Error: coordinates must exist to estimate overlap" unless ($l1 && $r1 && $l2 && $r2); if ($r1 - $l2 >= 0) { return 1; } else { return 0; } } #========================================================================== #Extract sequence in 1-letter code from the ATOM section sub extract_atom_seq_1 { my ($self, $chain) = @_; my $seq = ""; foreach my $idx (sort {$a <=> $b} keys %{ $self->atom_seq1->{$chain} }) { $seq .= $self->atom_seq1->{$chain}->{$idx}; } die "Error: could not extract seq from ATOM section" unless ($seq); return $seq; } #========================================================================== #Trim blanks from the begnning and end of a string sub trim { my ($self, $string) = @_; die "Error: string passed to trim can't be empty\n" unless ($string); #triming $string =~ s/^\s+//; $string =~ s/\s+$//; return $string; } #========================================================================== #The help for this class sub help { my $self = shift; my $help = << 'HELP'; HELP print $help; exit; } 1;
SaierLaboratory/TCDBtools
perl-modules/TCDB/PDB/CutHelixBundle.pm
Perl
bsd-3-clause
11,487
#!/usr/bin/perl package ConfigISIS_Cisco; use Data::Dumper; use strict; use CiscoTypes; use ConfigCommon; use ConfigParse; use ConfigDB; require Exporter; use vars(qw(@ISA @EXPORT $configdir @isis_db_tables)); @ISA = ('Exporter'); my $debug = 1; ###################################################################### # Constructor sub new { my ($class) = @_; my $self = {}; bless($self, $class); $self->{dbh} = &dbhandle($config_isis); $self->{nodes}; # array of router names $self->{edges}; # router_name => adjacency list (router nmes) $self->{router_options}; # router_name => reference(option_name => option_value) $self->{router_interfaces}; # router_name => reference(interface_name # => reference(data_type => value)) $self->{mesh_groups} = {}; # mesh_group_number => @mesh_group $self->{parse_errors}; return $self; } ###################################################################### # sub getNodes { my $self = shift; print "Config dir is: $configdir\n"; # each node will have # 1. a unique name # 2. predefined "programs" (i.e., route maps) my @rfiles = <$configdir/*-confg>; print STDERR "Looping through router files.\n" if $debug; foreach my $rfile (@rfiles) { print STDERR "Looking for $rfile.\n" if $debug; if ($rfile =~ /^.*\/(.*)-confg/){ print STDERR "Found $rfile.\n" if $debug; push(@{$self->{nodes}}, $1); } } } ###################################################################### # get unidirectional edges in the IS-IS graph # For each router, get the router's interfaces configured for IS-IS # Determine each interface's address # Match up addresses to nodes to get edges sub getInterfaces { my $self = shift; foreach my $router (@{$self->{nodes}}) { # interface_name => (data_type => data) my %interfaces; # add this to the hash $self->{router_interfaces}->{$router} = \%interfaces; # options $self->{router_options}->{$router}->{"isis_disabled"} = 0; $self->{router_options}->{$router}->{"wide_metrics_only_lvl1"} = 0; $self->{router_options}->{$router}->{"wide_metrics_only_lvl2"} = 0; $self->{router_options}->{$router}->{"auth_type"} = "none"; # add more here # Open the file for parsing my $rfilename = $configdir . "/" . $router . "-confg"; print STDERR "ConfigISIS_Cisco: Looking at $rfilename.\n" if $debug; open (RFILE, "$rfilename") || die "can't open $rfilename: $!\n"; # Parse the file while (<RFILE>) { chomp; my $line = $_; # Look for interfaces if ($line =~ /^interface\s+(.*)/) { my $intf_name = $1; print STDERR "Found interface: $intf_name.\n" if $debug; my $isis_enabled = 0; my %interface_data; $interface_data{"ipv4_address"}="none"; $interface_data{"ipv6_address"}="none"; $interface_data{"iso_address"}="none"; $interface_data{"lvl1_metric"}=10; $interface_data{"lvl2_metric"}=10; $interface_data{"lvl1_enabled"}=1; $interface_data{"lvl2_enabled"}=1; $interface_data{"mtu_ipv4"}=0; $interface_data{"mtu_ipv6"}=0; $interface_data{"mtu_iso"}=0; getDefaultMTU($intf_name, \%interface_data); # start parsing other configuration information my $intf_line; do { $intf_line = <RFILE>; chomp; # check if IS-IS is configured for this interface if ($intf_line =~ /^\s*ip\srouter\sisis/) { $isis_enabled = 1; } # IP address if ($intf_line =~ /$ip_mask_regexp/) { my $addr = $1; my $mask = $2; if ($addr != '') { $interface_data{"ipv4_address"} = calculateSubnetIP($addr,$mask); } } # ISO address if ($intf_line =~ /^\s*net\s+(.*)/) { $interface_data{"iso_address"} = $1; } # Routing level if ($intf_line =~ /^\s*isis\scircuit-type\slevel-1/) { $interface_data{"lvl1_enabled"}=1; $interface_data{"lvl2_enabled"}=0; } if ($intf_line =~ /^\s*isis\scircuit-type\slevel-1-2/) { # this is the default, do nothing } if ($intf_line =~ /^\s*isis\scircuit-type\slevel-2-only/) { $interface_data{"lvl1_enabled"}=0; $interface_data{"lvl2_enabled"}=1; } # Routing metric if ($intf_line =~ /^\s*isis\smetric\s(.*)\slevel-1/) { $interface_data{"lvl1_metric"}=$1; } elsif ($intf_line =~ /^\s*isis\smetric\s(.*)\slevel-2/) { $interface_data{"lvl2_metric"}=$1; } elsif ($intf_line =~ /^\s*isis\smetric\s(.*)/) { # if no level is specified, use level 1 $interface_data{"lvl1_metric"}=$1; } # MTU if ($intf_line =~ /mtu\s(.*)/) { $interface_data{"mtu_ipv4"}=$1; } # Mesh Groups if ($intf_line =~ /^\s*isis\smesh-group\s(.*)/) { my $mesh_num = $1; # check to see if this mesh group exists, and if so, # add this router push(@{$self->{mesh_groups}->{$mesh_num}}, $router . "\\" . $intf_name); } } while (($intf_line !~ /$eos/) && $intf_line); if ($isis_enabled == 1) { # add this interface $self->{router_interfaces}->{$router}->{$intf_name} = \%interface_data; } } # Router IS-IS settings elsif ($line =~ /^router\sisis/) { my $router_line; do { $router_line = <RFILE>; chomp; # ISO address if ($router_line =~ /^\s*net\s+(.*)/) { $self->{router_interfaces}->{"Loopback"}->{"iso_address"} = $1; } } while (($router_line !~ /$eos/) && $router_line); } } foreach my $interface (keys(%interfaces)) { # insert info into table my $cmd = "INSERT into $router_interfaces values ('$router','$interface','$interfaces{$interface}->{ipv4_address}','$interfaces{$interface}->{ipv6_address}','$interfaces{$interface}->{iso_address}','$interfaces{$interface}->{lvl1_enabled}','$interfaces{$interface}->{lvl2_enabled}','$interfaces{$interface}->{lvl1_metric}','$interfaces{$interface}->{lvl2_metric}','$interfaces{$interface}->{mtu_ipv4}','$interfaces{$interface}->{mtu_ipv6}','$interfaces{$interface}->{mtu_iso}')"; $self->{dbh}->do($cmd); } } } ###################################################################### # Get IS-IS network graph edges sub getEdges { my $self = shift; # Now generate the IS-IS network topological graph's edges foreach my $router (@{$self->{nodes}}) { # Get subnet addresses for each router my $subnet_addrs = $self->{dbh}->selectcol_arrayref("SELECT ipv4_address FROM $router_interfaces WHERE router_name='$router' AND interface_name NOT REGEXP 'Loopback.*'"); # Loop over these subnet addrs and find other routers # with the same subnet addrs foreach my $addr (@{$subnet_addrs}) { # skip if $addr = none if ($addr eq "none") { next; } my $neighbor_routers = $self->{dbh}->selectcol_arrayref("SELECT router_name FROM $router_interfaces WHERE ipv4_address='$addr'"); # Insert adjacencies into 'adjacencies' table foreach my $neighbor (@{$neighbor_routers}) { # no loops back to self if ($neighbor eq $router) { next; } my @metrics_and_intf = $self->{dbh}->selectrow_array("SELECT level1_metric,level2_metric, interface_name FROM $router_interfaces WHERE router_name='$router' AND ipv4_address='$addr'"); # determine level of adjacency my @origin_isis_levels = $self->{dbh}->selectrow_array("SELECT level1_routing, level2_routing FROM $router_interfaces WHERE router_name='$router' AND ipv4_address='$addr'"); my @neighbor_isis_levels = $self->{dbh}->selectrow_array("SELECT level1_routing, level2_routing FROM $router_interfaces WHERE router_name='$neighbor' AND ipv4_address='$addr'"); my $level1 = 0; my $level2 = 0; if ($origin_isis_levels[0] eq $neighbor_isis_levels[0]) { my $level1 = 1; } if ($origin_isis_levels[1] eq $neighbor_isis_levels[1]) { my $level2 = 1; } # determine if adjacency is inter-area my @origin_area_addr = $self->{dbh}->selectrow_array("SELECT iso_address FROM $router_info WHERE router_name = '$router'"); my @neighbor_area_addr = $self->{dbh}->selectrow_array("SELECT iso_address FROM $router_info WHERE router_name = '$neighbor'"); my $interarea = 0; if (!($origin_area_addr[0] eq $neighbor_area_addr[0])) { $interarea = 1; } my $cmd = "INSERT into $adjacencies VALUES ('$router','$neighbor',$metrics_and_intf[0],$metrics_and_intf[1],'$addr','$metrics_and_intf[2]','$level1','$level2','$interarea')"; $self->{dbh}->do($cmd); } } } } ###################################################################### # Organize Router Info for each router sub getRouterInfo { my $self = shift; foreach my $router (@{$self->{nodes}}) { # Query DB for loopback interface my @router_info = $self->{dbh}->selectrow_array("SELECT iso_address,ipv4_address,ipv6_address FROM $router_interfaces WHERE interface_name REGEXP 'Loopback.*' and router_name = '$router'"); # Compute Area address from ISO address my @addr_parts = split(/\./, $router_info[0]); my $area = $addr_parts[0] . "." . $addr_parts[1]; # insert into 'router_info' table my $cmd = "INSERT INTO $router_info VALUES ('$router','$router_info[0]','$router_info[1]','$router_info[2]','$area','$self->{router_options}->{$router}->{auth_type}','$self->{router_options}->{$router}->{auth_key}')"; $self->{dbh}->do($cmd); } } ###################################################################### # Get Mesh Groups sub getMeshGroups { my $self = shift; foreach my $mesh_num (keys(%{$self->{mesh_groups}})) { foreach my $member (@{$self->{mesh_groups}->{$mesh_num}}) { my @member_info = split(/\\/, $member); my $cmd = "INSERT INTO $mesh_groups VALUES ('$mesh_num', '$member_info[0]', '$member_info[1]')"; $self->{dbh}->do($cmd); } } } ###################################################################### sub calculateSubnetIP { my ($ip, $mask) = @_; print STDERR "Address is $ip.\n" if $debug; my @ip_parts = split(/\./,$ip); my @mask_parts = split(/\./,$mask);; # Bitwise And the IP and the mask together my @subnet_ip_parts; for (my $i = 0; $i < 4; $i++) { $subnet_ip_parts[$i] = $ip_parts[$i] & $mask_parts[$i]; } my $subnet_ip = join(".",@subnet_ip_parts); return $subnet_ip; } ###################################################################### # Data from Table 15-10, Cisco IOS in a Nutshell sub getDefaultMTU { my ($name, $data) = @_; if ($name =~ /Serial/) { $$data{"mtu_ipv4"} = 1500; $$data{"mtu_ipv6"} = 1500; $$data{"mtu_iso"} = 1500; } elsif ($name =~ /Ethernet/) { $$data{"mtu_ipv4"} = 1500; $$data{"mtu_ipv6"} = 1500; $$data{"mtu_iso"} = 1500; } else { $$data{"mtu_ipv4"} = 4470; $$data{"mtu_ipv6"} = 4470; $$data{"mtu_iso"} = 4470; } } 1;
wenhuizhang/rcc
perl/lib/ConfigISIS_Cisco.pm
Perl
mit
10,920
/* * Copyright (C) 2002, 2007 Christoph Wernhard * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, see <http://www.gnu.org/licenses/>. */ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% %%%% Queries %%%% %%%% Queries useful in different contexts. %%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% :- module(queries, [tp_direct_sub_of/4, tp_equal/4, tp_graph/3, tp_lessq/4, min_class/4, min_property/4]). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% %%%% Transitive Properties %%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% %%%% The transitive property (e.g. rdfs_subClassOf, rdfs_subPropertyOf) TP %%%% is assumed to actually transitively closed in all of these predicates. %%%% %%%% %%%% tp_direct_sub_of(+K, +TP, ?X, ?X1) %%%% %%%% The direct relation of a transitive property TP (e.g. direct subclass). %%%% %%%% Call examples: direct_sub_of(kb1, rdfs_subClassOf, C, C1) :- %%%% direct_sub_of(kb1, rdfs_subPropertyOf, P, P1) :- %%%% tp_direct_sub_of(KB, rdfs_subClassOf, X, X1) :- !, fact(KB, X, sys_directSubClassOf, X1). tp_direct_sub_of(KB, rdfs_subPropertyOf, X, X1) :- !, fact(KB, X, sys_directSubPropertyOf, X1). tp_direct_sub_of(KB, TP, X, X1) :- fact(KB, X, TP, X1), X \= X1, \+ ( fact(KB, X, TP, X2), X2 \= X, X2 \= X1, fact(KB, X2, TP, X1), \+ fact(KB, X2, TP, X), \+ fact(KB, X1, TP, X2) ). %%%% %%%% tp_equal(+K, +TP, ?X, ?X1) %%%% %%%% The equality relation of a transitive property TP. Excludes syntactic %%%% equality. Symmetrically closed. %%%% tp_equal(KB, TP, X, X1) :- X \= X1, fact(KB, X, TP, X1), fact(KB, X1, TP, X). %%%% %%%% tp_graph(KB, TP, Graph) %%%% %%%% Returns a P-Graph of the direct relation corresponding to the direct %%%% relationship. Equal nodes are identified and represented by terms %%%% equal(Nodes), where nodes is the ordered list of identified nodes. %%%% tp_graph(KB, TP, Graph) :- tp_equal_table(KB, TP, Table), ( setof( X1-X2, tp_graph_edge(KB, TP, Table, X1, X2), Graph ) -> true ; Graph = [] ). tp_equal_table(KB, TP, Table) :- setof(X-equal(X1s), setof(X1, tp_equal(KB, TP, X, X1), X1s), Table), !. tp_equal_table(_, _, []). tp_graph_edge(KB, TP, Table, X1, X2) :- tp_direct_sub_of(KB, TP, X3, X4), ( memberchk(X3-X1, Table) -> true ; X1 = X3 ), ( memberchk(X4-X2, Table) -> true ; X2 = X4 ). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% %%%% Minimal Relationships %%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% %%%% min_class(+K, ?S, ?P, ?C) %%%% min_property(+K, ?S, ?P, ?O) %%%% %%%% The given relationship, minimized with respect to rdfs_subClassOf or %%%% and rdfs_subPropertyOf. Examples: %%%% %%%% min_class(kb, s, rdf_type, C) - the direct types of s %%%% min_class(kb, p, sys_domain, C) - the direct domains of p %%%% min_class(kb, p, sys_range, C) - the direct ranges of p %%%% min_property(kb, s, P, O) - gives only "minimal" properties of s, e.g. %%%% only the "father" is returned, and not the %%%% same object as "parent" too. %%%% min_class(KB, S, P, C) :- fact(KB, S, P, C), \+ ( fact(KB, S, P, C1), C1 \= C, fact(KB, C1, rdfs_subClassOf, C), \+ fact(KB, C, rdfs_subClassOf, C1) ). min_property(KB, S, P, O) :- fact(KB, S, P, O), \+ ( fact(KB, S, P1, O), P1 \= P, fact(KB, P1, rdfs_subPropertyOf, P), \+ fact(KB, P, rdfs_subPropertyOf, P1) ). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% %%%% tp_lessq(+KB, +TP, +X1, -X2) %%%% tp_lessq(+KB, +TP, -X1, +X2) %%%% tp_lessq(+KB, +TP, +X1, +X2) %%%% tp_lessq(KB, TP, X1, X2) :- ( X1 = X2 ; X1 \== X2, fact(KB, X1, TP, X2), X1 \== X2 ).
TeamSPoon/logicmoo_base
prolog/logicmoo/tptp/infra/src/queries.pl
Perl
mit
4,554
# Copyright 2014 - present MongoDB, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. use 5.010; use strict; use warnings; package MongoDBTest::Mongod; use Moo; use Types::Path::Tiny qw/AbsDir/; use namespace::clean; with 'MooseX::Role::Logger', 'MongoDBTest::Role::Server'; has datadir => ( is => 'lazy', isa => AbsDir, coerce => AbsDir->coercion, ); sub _build_datadir { my ($self) = @_; my $dir = $self->tempdir->child("data"); $dir->mkpath; return $dir; } sub _build_command_name { return 'mongod' } sub _build_command_args { my ($self) = @_; return "--dbpath " . $self->datadir; } 1;
dagolden/mongo-perl-driver
devel/lib/MongoDBTest/Mongod.pm
Perl
apache-2.0
1,141
use utf8; # # Copyright 2015 Comcast Cable Communications Management, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # package Schema::Result::DeliveryServiceInfoForServerList; # this view returns the regexp set for a delivery services, ordered by type, set_number. # to use, do # # $rs = $self->db->resultset('DeliveryServiceInfoForServerList')->search({}, { bind => [ \$server ]}); # # where $id is the deliveryservice id. use strict; use warnings; use base 'DBIx::Class::Core'; __PACKAGE__->table_class('DBIx::Class::ResultSource::View'); __PACKAGE__->table("DeliveryServiceInfoForServerList:"); __PACKAGE__->result_source_instance->is_virtual(1); __PACKAGE__->result_source_instance->view_definition( " SELECT DISTINCT deliveryservice.xml_id AS xml_id, deliveryservice.id AS ds_id, deliveryservice.dscp AS dscp, deliveryservice.signed AS signed, deliveryservice.qstring_ignore AS qstring_ignore, deliveryservice.org_server_fqdn as org_server_fqdn, deliveryservice.multi_site_origin as multi_site_origin, deliveryservice.range_request_handling as range_request_handling, deliveryservice.origin_shield as origin_shield, regex.pattern AS pattern, retype.name AS re_type, dstype.name AS ds_type, parameter.value AS domain_name, deliveryservice_regex.set_number AS set_number, deliveryservice.edge_header_rewrite as edge_header_rewrite, deliveryservice.regex_remap as regex_remap, deliveryservice.cacheurl as cacheurl, deliveryservice.remap_text as remap_text, mid_header_rewrite as mid_header_rewrite, deliveryservice.protocol as protocol FROM deliveryservice JOIN deliveryservice_regex ON deliveryservice_regex.deliveryservice = deliveryservice.id JOIN regex ON deliveryservice_regex.regex = regex.id JOIN type as retype ON regex.type = retype.id JOIN type as dstype ON deliveryservice.type = dstype.id JOIN profile_parameter ON deliveryservice.profile = profile_parameter.profile JOIN parameter ON parameter.id = profile_parameter.parameter JOIN deliveryservice_server ON deliveryservice_server.deliveryservice = deliveryservice.id JOIN server ON deliveryservice_server.server = server.id WHERE parameter.name = 'domain_name' AND server.id IN (?) ORDER BY ds_id, re_type , deliveryservice_regex.set_number " ); __PACKAGE__->add_columns( "xml_id", { data_type => "varchar", is_nullable => 0, size => 45 }, "org_server_fqdn", { data_type => "varchar", is_nullable => 0, size => 45 }, "multi_site_origin", { data_type => "integer", is_nullable => 0 }, "ds_id", { data_type => "integer", is_nullable => 0 }, "dscp", { data_type => "integer", is_nullable => 0 }, "signed", { data_type => "integer", is_nullable => 0 }, "qstring_ignore", { data_type => "integer", is_nullable => 0 }, "pattern", { data_type => "varchar", is_nullable => 0, size => 45 }, "re_type", { data_type => "varchar", is_nullable => 0, size => 45 }, "ds_type", { data_type => "varchar", is_nullable => 0, size => 45 }, "set_number", { data_type => "integer", is_nullable => 0 }, "domain_name", { data_type => "varchar", is_nullable => 0, size => 45 }, "edge_header_rewrite", { data_type => "varchar", is_nullable => 0, size => 1024 }, "mid_header_rewrite", { data_type => "varchar", is_nullable => 0, size => 1024 }, "regex_remap", { data_type => "varchar", is_nullable => 0, size => 1024 }, "cacheurl", { data_type => "varchar", is_nullable => 0, size => 1024 }, "remap_text", { data_type => "varchar", is_nullable => 0, size => 2048 }, "protocol", { data_type => "tinyint", is_nullable => 0, size => 4 }, "range_request_handling", { data_type => "tinyint", is_nullable => 0, size => 4 }, "origin_shield", { data_type => "varchar", is_nullable => 0, size => 1024 }, ); 1;
dewrich/traffic_control
traffic_ops/app/lib/Schema/Result/DeliveryServiceInfoForServerList.pm
Perl
apache-2.0
4,549
# This file is auto-generated by the Perl DateTime Suite time zone # code generator (0.07) This code generator comes with the # DateTime::TimeZone module distribution in the tools/ directory # # Generated from /tmp/rnClxBLdxJ/northamerica. Olson data version 2013a # # Do not edit this file directly. # package DateTime::TimeZone::America::St_Vincent; { $DateTime::TimeZone::America::St_Vincent::VERSION = '1.57'; } use strict; use Class::Singleton 1.03; use DateTime::TimeZone; use DateTime::TimeZone::OlsonDB; @DateTime::TimeZone::America::St_Vincent::ISA = ( 'Class::Singleton', 'DateTime::TimeZone' ); my $spans = [ [ DateTime::TimeZone::NEG_INFINITY, # utc_start 59611176296, # utc_end 1890-01-01 04:04:56 (Wed) DateTime::TimeZone::NEG_INFINITY, # local_start 59611161600, # local_end 1890-01-01 00:00:00 (Wed) -14696, 0, 'LMT', ], [ 59611176296, # utc_start 1890-01-01 04:04:56 (Wed) 60305313896, # utc_end 1912-01-01 04:04:56 (Mon) 59611161600, # local_start 1890-01-01 00:00:00 (Wed) 60305299200, # local_end 1912-01-01 00:00:00 (Mon) -14696, 0, 'KMT', ], [ 60305313896, # utc_start 1912-01-01 04:04:56 (Mon) DateTime::TimeZone::INFINITY, # utc_end 60305299496, # local_start 1912-01-01 00:04:56 (Mon) DateTime::TimeZone::INFINITY, # local_end -14400, 0, 'AST', ], ]; sub olson_version { '2013a' } sub has_dst_changes { 0 } sub _max_year { 2023 } sub _new_instance { return shift->_init( @_, spans => $spans ); } 1;
Dokaponteam/ITF_Project
xampp/perl/vendor/lib/DateTime/TimeZone/America/St_Vincent.pm
Perl
mit
1,504
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. package AI::MXNet::KVStore; use strict; use warnings; use AI::MXNet::Base; use AI::MXNet::NDArray; use AI::MXNet::Optimizer; use MIME::Base64; use Storable; use Mouse; use AI::MXNet::Function::Parameters; =head1 NAME AI::MXNet::KVStore - Key value store interface of MXNet. =head1 DESCRIPTION Key value store interface of MXNet for parameter synchronization, over multiple devices. =cut has 'handle' => (is => 'ro', isa => 'KVStoreHandle', required => 1); has '_updater' => (is => 'rw', isa => 'AI::MXNet::Updater'); has '_updater_func' => (is => 'rw', isa => 'CodeRef'); sub DEMOLISH { check_call(AI::MXNetCAPI::KVStoreFree(shift->handle)); } =head2 init Initialize a single or a sequence of key-value pairs into the store. For each key, one must init it before push and pull. Only worker 0's (rank == 0) data are used. This function returns after data have been initialized successfully Parameters ---------- key : str or an array ref of str The keys. value : NDArray or an array ref of NDArray objects The values. Examples -------- >>> # init a single key-value pair >>> $shape = [2,3] >>> $kv = mx->kv->create('local') >>> $kv->init(3, mx->nd->ones($shape)*2) >>> $a = mx->nd->zeros($shape) >>> $kv->pull(3, out=>$a) >>> print $a->aspdl [[ 2 2 2] [ 2 2 2]] >>> # init a list of key-value pairs >>> $keys = [5, 7, 9] >>> $kv->init(keys, [map { mx->nd->ones($shape) } 0..@$keys-1]) =cut method init( Str|ArrayRef[Str] $key, AI::MXNet::NDArray|ArrayRef[AI::MXNet::NDArray]|ArrayRef[ArrayRef[AI::MXNet::NDArray]] $value ) { my ($keys, $vals) = _key_value($key, $value); check_call( AI::MXNetCAPI::KVStoreInitEx( $self->handle, scalar(@{ $keys }), $keys, $vals ) ); } =head2 push Push a single or a sequence of key-value pairs into the store. Data consistency: 1. this function returns after adding an operator to the engine. 2. push is always called after all previous push and pull on the same key are finished. 3. there is no synchronization between workers. One can use _barrier() to sync all workers. Parameters ---------- key : str or array ref of str value : NDArray or array ref of NDArray or array ref of array refs of NDArray priority : int, optional The priority of the push operation. The higher the priority, the faster this action is likely to be executed before other push actions. Examples -------- >>> # push a single key-value pair >>> $kv->push(3, mx->nd->ones($shape)*8) >>> $kv->pull(3, out=>$a) # pull out the value >>> print $a->aspdl() [[ 8. 8. 8.] [ 8. 8. 8.]] >>> # aggregate the value and the push >>> $gpus = [map { mx->gpu($_) } 0..3] >>> $b = [map { mx->nd->ones($shape, ctx => $_) } @$gpus] >>> $kv->push(3, $b) >>> $kv->pull(3, out=>$a) >>> print $a->aspdl [[ 4. 4. 4.] [ 4. 4. 4.]] >>> # push a list of keys. >>> # single device >>> $kv->push($keys, [map { mx->nd->ones($shape) } 0..@$keys-1) >>> $b = [map { mx->nd->zeros(shape) } 0..@$keys-1] >>> $kv->pull($keys, out=>$b) >>> print $b->[1]->aspdl [[ 1. 1. 1.] [ 1. 1. 1.]] >>> # multiple devices: >>> $b = [map { [map { mx->nd->ones($shape, ctx => $_) } @$gpus] } @$keys-1] >>> $kv->push($keys, $b) >>> $kv->pull($keys, out=>$b) >>> print $b->[1][1]->aspdl() [[ 4. 4. 4.] [ 4. 4. 4.]] =cut method push( Str|ArrayRef[Str] $key, AI::MXNet::NDArray|ArrayRef[AI::MXNet::NDArray]|ArrayRef[ArrayRef[AI::MXNet::NDArray]] $value, Int :$priority=0 ) { my ($keys, $vals) = _key_value($key, $value); check_call( AI::MXNetCAPI::KVStorePushEx( $self->handle, scalar(@{ $keys }), $keys, $vals, $priority ) ); } =head2 pull Pull a single value or a sequence of values from the store. Data consistency: 1. this function returns after adding an operator to the engine. But any further read on out will be blocked until it is finished. 2. pull is always called after all previous push and pull on the same key are finished. 3. It pulls the newest value from the store. Parameters ---------- key : str or array ref of str Keys out: NDArray or array ref of NDArray or array ref of array refs of NDArray According values priority : int, optional The priority of the push operation. The higher the priority, the faster this action is likely to be executed before other push actions. Examples -------- >>> # pull a single key-value pair >>> $a = mx->nd->zeros($shape) >>> $kv->pull(3, out=>$a) >>> print $a->aspdl [[ 2. 2. 2.] [ 2. 2. 2.]] >>> # pull into multiple devices >>> $b = [map { mx->nd->ones($shape, $_) } @$gpus] >>> $kv->pull(3, out=>$b) >>> print $b->[1]->aspdl() [[ 2. 2. 2.] [ 2. 2. 2.]] >>> # pull a list of key-value pairs. >>> # On single device >>> $keys = [5, 7, 9] >>> $b = [map { mx->nd->zeros($shape) } 0..@$keys-1] >>> $kv->pull($keys, out=>$b) >>> print $b->[1]->aspdl() [[ 2. 2. 2.] [ 2. 2. 2.]] >>> # On multiple devices >>> $b = [map { [map { mx->nd->ones($shape, ctx => $_) } @$gpus ] } 0..@$keys-1] >>> $kv->pull($keys, out=>$b) >>> print $b->[1][1]->aspdl() [[ 2. 2. 2.] [ 2. 2. 2.]] =cut method pull( Str|ArrayRef[Str] $key, AI::MXNet::NDArray|ArrayRef[AI::MXNet::NDArray]|ArrayRef[ArrayRef[AI::MXNet::NDArray]] :$out, Int :$priority=0 ) { my ($keys, $vals) = _key_value($key, $out); check_call( AI::MXNetCAPI::KVStorePullEx( $self->handle, scalar(@{ $keys }), $keys, $vals, $priority ) ); } =head2 row_sparse_pull Pulls a single AI::MXNet::NDArray::RowSparse value or an array ref of AI::MXNet::NDArray::RowSparse values from the store with specified row_ids. When there is only one row_id, KVStoreRowSparsePull is invoked just once and the result is broadcast to all the rest of outputs. `row_sparse_pull` is executed asynchronously after all previous `pull`/`row_sparse_pull` calls and the last `push` call for the same input key(s) are finished. The returned values are guaranteed to be the latest values in the store. Parameters ---------- key : str, int, or sequence of str or int Keys. out: AI::MXNet::NDArray::RowSparse or array ref of AI::MXNet::NDArray::RowSparse or array ref of array ref of AI::MXNet::NDArray::RowSparse Values corresponding to the keys. The stype is expected to be row_sparse priority : int, optional The priority of the pull operation. Higher priority pull operations are likely to be executed before other pull actions. row_ids : AI::MXNet::NDArray or array ref of AI::MXNet::NDArray The row_ids for which to pull for each value. Each row_id is an 1D NDArray whose values don't have to be unique nor sorted. Examples -------- >>> $shape = [3, 3] >>> $kv->init('3', mx->nd->ones($shape)->tostype('row_sparse')) >>> $a = mx->nd->sparse->zeros('row_sparse', $shape) >>> $row_ids = mx->nd->array([0, 2], dtype=>'int64') >>> $kv->row_sparse_pull('3', out=>$a, row_ids=>$row_ids) >>> print $a->aspdl [[ 1. 1. 1.] [ 0. 0. 0.] [ 1. 1. 1.]] >>> $duplicate_row_ids = mx->nd->array([2, 2], dtype=>'int64') >>> $kv->row_sparse_pull('3', out=>$a, row_ids=>$duplicate_row_ids) >>> print $a->aspdl [[ 0. 0. 0.] [ 0. 0. 0.] [ 1. 1. 1.]] >>> $unsorted_row_ids = mx->nd->array([1, 0], dtype=>'int64') >>> $kv->row_sparse_pull('3', out=>$a, row_ids=>$unsorted_row_ids) >>> print $a->aspdl [[ 1. 1. 1.] [ 1. 1. 1.] [ 0. 0. 0.]] =cut method row_sparse_pull( Str|ArrayRef[Str] $key, AI::MXNet::NDArray::RowSparse|ArrayRef[AI::MXNet::NDArray::RowSparse]|ArrayRef[ArrayRef[AI::MXNet::NDArray::RowSparse]] :$out, Int :$priority=0, AI::MXNet::NDArray|ArrayRef[AI::MXNet::NDArray]|ArrayRef[ArrayRef[AI::MXNet::NDArray]] :$row_ids ) { if(blessed $row_ids) { $row_ids = [$row_ids]; } my $first_out = $out; # whether row_ids are the same my $single_rowid = 0; if(@$row_ids == 1 and ref $out eq 'ARRAY') { $single_rowid = 1; $first_out = [$out->[0]]; } my ($ckeys, $cvals) = _key_value($key, $first_out); my (undef, $crow_ids) = _key_value($key, $row_ids); assert( (@$crow_ids == @$cvals), "the number of row_ids doesn't match the number of values" ); check_call( AI::MXNetCAPI::KVStorePullRowSparseEx( $self->handle, scalar(@$ckeys), $ckeys, $cvals, $crow_ids, $priority ) ); # the result can be copied to other devices without invoking row_sparse_pull # if the indices are the same if($single_rowid) { for my $out_i (@{ $out } [1..@{ $out }-1]) { $out->[0]->copyto($out_i); } } } =head2 set_gradient_compression Specifies type of low-bit quantization for gradient compression \ and additional arguments depending on the type of compression being used. 2bit Gradient Compression takes a positive float `threshold`. The technique works by thresholding values such that positive values in the gradient above threshold will be set to threshold. Negative values whose absolute values are higher than threshold, will be set to the negative of threshold. Values whose absolute values are less than threshold will be set to 0. By doing so, each value in the gradient is in one of three states. 2bits are used to represent these states, and every 16 float values in the original gradient can be represented using one float. This compressed representation can reduce communication costs. The difference between these thresholded values and original values is stored at the sender's end as residual and added to the gradient in the next iteration. When kvstore is 'local', gradient compression is used to reduce communication between multiple devices (gpus). Gradient is quantized on each GPU which computed the gradients, then sent to the GPU which merges the gradients. This receiving GPU dequantizes the gradients and merges them. Note that this increases memory usage on each GPU because of the residual array stored. When kvstore is 'dist', gradient compression is used to reduce communication from worker to sender. Gradient is quantized on each worker which computed the gradients, then sent to the server which dequantizes this data and merges the gradients from each worker. Note that this increases CPU memory usage on each worker because of the residual array stored. Only worker to server communication is compressed in this setting. If each machine has multiple GPUs, currently this GPU to GPU or GPU to CPU communication is not compressed. Server to worker communication (in the case of pull) is also not compressed. To use 2bit compression, we need to specify `type` as `2bit`. Only specifying `type` would use default value for the threshold. To completely specify the arguments for 2bit compression, we would need to pass a dictionary which includes `threshold` like: {'type': '2bit', 'threshold': 0.5} Parameters ---------- compression_params : HashRef A dictionary specifying the type and parameters for gradient compression. The key `type` in this dictionary is a required string argument and specifies the type of gradient compression. Currently `type` can be only `2bit` Other keys in this dictionary are optional and specific to the type of gradient compression. =cut method set_gradient_compression(HashRef[Str] $compression_params) { if($self->type =~ /(?:device|dist)/) { check_call( AI::MXNetCAPI::KVStoreSetGradientCompression( $self->handle, scalar(keys %$compression_params), $compression_params ) ); } else { confess('Gradient compression is not supported for this type of kvstore'); } } =head2 set_optimizer Register an optimizer to the store If there are multiple machines, this process (should be a worker node) will pack this optimizer and send it to all servers. It returns after this action is done. Parameters ---------- optimizer : Optimizer the optimizer =cut method set_optimizer(AI::MXNet::Optimizer $optimizer) { my $is_worker = check_call(AI::MXNetCAPI::KVStoreIsWorkerNode()); if($self->type =~ /dist/ and $is_worker) { my $optim_str = MIME::Base64::encode_base64(Storable::freeze($optimizer), ""); $self->_send_command_to_servers(0, $optim_str); } else { $self->_updater(AI::MXNet::Optimizer->get_updater($optimizer)); $self->_set_updater($self->_updater); } } =head2 type Get the type of this kvstore Returns ------- type : str the string type =cut method type() { return scalar(check_call(AI::MXNetCAPI::KVStoreGetType($self->handle))); } =head2 rank Get the rank of this worker node Returns ------- rank : int The rank of this node, which is in [0, get_num_workers()) =cut method rank() { return scalar(check_call(AI::MXNetCAPI::KVStoreGetRank($self->handle))); } =head2 num_workers Get the number of worker nodes Returns ------- size :int The number of worker nodes =cut method num_workers() { return scalar(check_call(AI::MXNetCAPI::KVStoreGetGroupSize($self->handle))); } =head2 save_optimizer_states Save optimizer (updater) state to file Parameters ---------- fname : str Path to output states file. dump_optimizer : bool, default False Whether to also save the optimizer itself. This would also save optimizer information such as learning rate and weight decay schedules. =cut method save_optimizer_states(Str $fname, Bool :$dump_optimizer=0) { confess("Cannot save states for distributed training") unless defined $self->_updater; open(F, ">:raw", "$fname") or confess("can't open $fname for writing: $!"); print F $self->_updater->get_states($dump_optimizer); close(F); } =head2 load_optimizer_states Load optimizer (updater) state from file. Parameters ---------- fname : str Path to input states file. =cut method load_optimizer_states(Str $fname) { confess("Cannot save states for distributed training") unless defined $self->_updater; open(F, "<:raw", "$fname") or confess("can't open $fname for reading: $!"); my $data; { local($/) = undef; $data = <F>; } close(F); $self->_updater->set_states($data); } =head2 _set_updater Set a push updater into the store. This function only changes the local store. Use set_optimizer for multi-machines. Parameters ---------- updater : function the updater function Examples -------- >>> my $update = sub { my ($key, input, stored) = @_; ... print "update on key: $key\n"; ... $stored += $input * 2; }; >>> $kv->_set_updater($update) >>> $kv->pull(3, out=>$a) >>> print $a->aspdl() [[ 4. 4. 4.] [ 4. 4. 4.]] >>> $kv->push(3, mx->nd->ones($shape)) update on key: 3 >>> $kv->pull(3, out=>$a) >>> print $a->aspdl() [[ 6. 6. 6.] [ 6. 6. 6.]] =cut method _set_updater(Updater $updater_func) { $self->_updater_func( sub { my ($index, $input_handle, $storage_handle) = @_; $updater_func->( $index, AI::MXNet::NDArray->_ndarray_cls($input_handle), AI::MXNet::NDArray->_ndarray_cls($storage_handle) ); } ); check_call( AI::MXNetCAPI::KVStoreSetUpdater( $self->handle, $self->_updater_func ) ); } =head2 _barrier Global barrier between all worker nodes. For example, assume there are n machines, we want to let machine 0 first init the values, and then pull the inited value to all machines. Before pulling, we can place a barrier to guarantee that the initialization is finished. =cut method _barrier() { check_call(AI::MXNetCAPI::KVStoreBarrier($self->handle)); } =head2 _send_command_to_servers Send a command to all server nodes Send a command to all server nodes, which will make each server node run KVStoreServer.controller This function returns after the command has been executed in all server nodes. Parameters ---------- head : int the head of the command body : str the body of the command =cut method _send_command_to_servers(Int $head, Str $body) { check_call( AI::MXNetCAPI::KVStoreSendCommmandToServers( $self->handle, $head, $body ) ); } =head2 create Create a new KVStore. Parameters ---------- name : {'local'} The type of KVStore - local works for multiple devices on a single machine (single process) - dist works for multi-machines (multiple processes) Returns ------- kv : KVStore The created AI::MXNet::KVStore =cut method create(Str $name='local') { my $handle = check_call(AI::MXNetCAPI::KVStoreCreate($name)); return __PACKAGE__->new(handle => $handle); } sub _key_value { my ($keys, $vals) = @_; if(not ref $keys) { if(blessed $vals) { return ([$keys], [$vals->handle]); } else { for my $value (@{ $vals }) { assert(blessed($value) and $value->isa('AI::MXNet::NDArray')); return ([($keys)x@$vals], [map { $_->handle } @$vals]); } } } else { assert(not blessed($vals) and @$keys == @$vals); my @c_keys; my @c_vals; for(zip($keys, $vals)) { my ($key, $val) = @$_; my ($c_key, $c_val) = _key_value($key, $val); push @c_keys, @$c_key; push @c_vals, @$c_val; } return (\@c_keys, \@c_vals); } } 1;
jiajiechen/mxnet
perl-package/AI-MXNet/lib/AI/MXNet/KVStore.pm
Perl
apache-2.0
19,907
########################################################################### # # This file is auto-generated by the Perl DateTime Suite locale # generator (0.05). This code generator comes with the # DateTime::Locale distribution in the tools/ directory, and is called # generate-from-cldr. # # This file as generated from the CLDR XML locale data. See the # LICENSE.cldr file included in this distribution for license details. # # This file was generated from the source file ru_RU.xml # The source file version number was 1.52, generated on # 2009/05/05 23:06:39. # # Do not edit this file directly. # ########################################################################### package DateTime::Locale::ru_RU; use strict; use warnings; use utf8; use base 'DateTime::Locale::ru'; sub cldr_version { return "1\.7\.1" } { my $first_day_of_week = "1"; sub first_day_of_week { return $first_day_of_week } } { my $glibc_date_format = "\%d\.\%m\.\%Y"; sub glibc_date_format { return $glibc_date_format } } { my $glibc_date_1_format = "\%a\ \%b\ \%e\ \%H\:\%M\:\%S\ \%Z\ \%Y"; sub glibc_date_1_format { return $glibc_date_1_format } } { my $glibc_datetime_format = "\%a\ \%d\ \%b\ \%Y\ \%T"; sub glibc_datetime_format { return $glibc_datetime_format } } { my $glibc_time_format = "\%T"; sub glibc_time_format { return $glibc_time_format } } 1; __END__ =pod =encoding utf8 =head1 NAME DateTime::Locale::ru_RU =head1 SYNOPSIS use DateTime; my $dt = DateTime->now( locale => 'ru_RU' ); print $dt->month_name(); =head1 DESCRIPTION This is the DateTime locale package for Russian Russia. =head1 DATA This locale inherits from the L<DateTime::Locale::ru> locale. It contains the following data. =head2 Days =head3 Wide (format) понедельник вторник среда четверг пятница суббота воскресенье =head3 Abbreviated (format) Пн Вт Ср Чт Пт Сб Вс =head3 Narrow (format) П В С Ч П С В =head3 Wide (stand-alone) Понедельник Вторник Среда Четверг Пятница Суббота Воскресенье =head3 Abbreviated (stand-alone) Пн Вт Ср Чт Пт Сб Вс =head3 Narrow (stand-alone) П В С Ч П С В =head2 Months =head3 Wide (format) января февраля марта апреля мая июня июля августа сентября октября ноября декабря =head3 Abbreviated (format) янв. февр. марта апр. мая июня июля авг. сент. окт. нояб. дек. =head3 Narrow (format) Я Ф М А М И И А С О Н Д =head3 Wide (stand-alone) Январь Февраль Март Апрель Май Июнь Июль Август Сентябрь Октябрь Ноябрь Декабрь =head3 Abbreviated (stand-alone) янв. февр. март апр. май июнь июль авг. сент. окт. нояб. дек. =head3 Narrow (stand-alone) Я Ф М А М И И А С О Н Д =head2 Quarters =head3 Wide (format) 1-й квартал 2-й квартал 3-й квартал 4-й квартал =head3 Abbreviated (format) 1-й кв. 2-й кв. 3-й кв. 4-й кв. =head3 Narrow (format) 1 2 3 4 =head3 Wide (stand-alone) 1-й квартал 2-й квартал 3-й квартал 4-й квартал =head3 Abbreviated (stand-alone) 1-й кв. 2-й кв. 3-й кв. 4-й кв. =head3 Narrow (stand-alone) 1 2 3 4 =head2 Eras =head3 Wide до н.э. н.э. =head3 Abbreviated до н.э. н.э. =head3 Narrow до н.э. н.э. =head2 Date Formats =head3 Full 2008-02-05T18:30:30 = вторник, 5 февраля 2008 г. 1995-12-22T09:05:02 = пятница, 22 декабря 1995 г. -0010-09-15T04:44:23 = суббота, 15 сентября -10 г. =head3 Long 2008-02-05T18:30:30 = 5 февраля 2008 г. 1995-12-22T09:05:02 = 22 декабря 1995 г. -0010-09-15T04:44:23 = 15 сентября -10 г. =head3 Medium 2008-02-05T18:30:30 = 05.02.2008 1995-12-22T09:05:02 = 22.12.1995 -0010-09-15T04:44:23 = 15.09.-010 =head3 Short 2008-02-05T18:30:30 = 05.02.08 1995-12-22T09:05:02 = 22.12.95 -0010-09-15T04:44:23 = 15.09.-10 =head3 Default 2008-02-05T18:30:30 = 05.02.2008 1995-12-22T09:05:02 = 22.12.1995 -0010-09-15T04:44:23 = 15.09.-010 =head2 Time Formats =head3 Full 2008-02-05T18:30:30 = 18:30:30 UTC 1995-12-22T09:05:02 = 9:05:02 UTC -0010-09-15T04:44:23 = 4:44:23 UTC =head3 Long 2008-02-05T18:30:30 = 18:30:30 UTC 1995-12-22T09:05:02 = 9:05:02 UTC -0010-09-15T04:44:23 = 4:44:23 UTC =head3 Medium 2008-02-05T18:30:30 = 18:30:30 1995-12-22T09:05:02 = 9:05:02 -0010-09-15T04:44:23 = 4:44:23 =head3 Short 2008-02-05T18:30:30 = 18:30 1995-12-22T09:05:02 = 9:05 -0010-09-15T04:44:23 = 4:44 =head3 Default 2008-02-05T18:30:30 = 18:30:30 1995-12-22T09:05:02 = 9:05:02 -0010-09-15T04:44:23 = 4:44:23 =head2 Datetime Formats =head3 Full 2008-02-05T18:30:30 = вторник, 5 февраля 2008 г. 18:30:30 UTC 1995-12-22T09:05:02 = пятница, 22 декабря 1995 г. 9:05:02 UTC -0010-09-15T04:44:23 = суббота, 15 сентября -10 г. 4:44:23 UTC =head3 Long 2008-02-05T18:30:30 = 5 февраля 2008 г. 18:30:30 UTC 1995-12-22T09:05:02 = 22 декабря 1995 г. 9:05:02 UTC -0010-09-15T04:44:23 = 15 сентября -10 г. 4:44:23 UTC =head3 Medium 2008-02-05T18:30:30 = 05.02.2008 18:30:30 1995-12-22T09:05:02 = 22.12.1995 9:05:02 -0010-09-15T04:44:23 = 15.09.-010 4:44:23 =head3 Short 2008-02-05T18:30:30 = 05.02.08 18:30 1995-12-22T09:05:02 = 22.12.95 9:05 -0010-09-15T04:44:23 = 15.09.-10 4:44 =head3 Default 2008-02-05T18:30:30 = 05.02.2008 18:30:30 1995-12-22T09:05:02 = 22.12.1995 9:05:02 -0010-09-15T04:44:23 = 15.09.-010 4:44:23 =head2 Available Formats =head3 d (d) 2008-02-05T18:30:30 = 5 1995-12-22T09:05:02 = 22 -0010-09-15T04:44:23 = 15 =head3 Ed (E d) 2008-02-05T18:30:30 = Вт 5 1995-12-22T09:05:02 = Пт 22 -0010-09-15T04:44:23 = Сб 15 =head3 EEEd (d EEE) 2008-02-05T18:30:30 = 5 Вт 1995-12-22T09:05:02 = 22 Пт -0010-09-15T04:44:23 = 15 Сб =head3 H (H) 2008-02-05T18:30:30 = 18 1995-12-22T09:05:02 = 9 -0010-09-15T04:44:23 = 4 =head3 HHmm (HH:mm) 2008-02-05T18:30:30 = 18:30 1995-12-22T09:05:02 = 09:05 -0010-09-15T04:44:23 = 04:44 =head3 HHmmss (HH:mm:ss) 2008-02-05T18:30:30 = 18:30:30 1995-12-22T09:05:02 = 09:05:02 -0010-09-15T04:44:23 = 04:44:23 =head3 Hm (H:mm) 2008-02-05T18:30:30 = 18:30 1995-12-22T09:05:02 = 9:05 -0010-09-15T04:44:23 = 4:44 =head3 hm (h:mm a) 2008-02-05T18:30:30 = 6:30 PM 1995-12-22T09:05:02 = 9:05 AM -0010-09-15T04:44:23 = 4:44 AM =head3 Hms (H:mm:ss) 2008-02-05T18:30:30 = 18:30:30 1995-12-22T09:05:02 = 9:05:02 -0010-09-15T04:44:23 = 4:44:23 =head3 hms (h:mm:ss a) 2008-02-05T18:30:30 = 6:30:30 PM 1995-12-22T09:05:02 = 9:05:02 AM -0010-09-15T04:44:23 = 4:44:23 AM =head3 M (L) 2008-02-05T18:30:30 = 2 1995-12-22T09:05:02 = 12 -0010-09-15T04:44:23 = 9 =head3 Md (d.M) 2008-02-05T18:30:30 = 5.2 1995-12-22T09:05:02 = 22.12 -0010-09-15T04:44:23 = 15.9 =head3 MEd (E, M-d) 2008-02-05T18:30:30 = Вт, 2-5 1995-12-22T09:05:02 = Пт, 12-22 -0010-09-15T04:44:23 = Сб, 9-15 =head3 MMdd (dd.MM) 2008-02-05T18:30:30 = 05.02 1995-12-22T09:05:02 = 22.12 -0010-09-15T04:44:23 = 15.09 =head3 MMM (LLL) 2008-02-05T18:30:30 = февр. 1995-12-22T09:05:02 = дек. -0010-09-15T04:44:23 = сент. =head3 MMMd (d MMM) 2008-02-05T18:30:30 = 5 февр. 1995-12-22T09:05:02 = 22 дек. -0010-09-15T04:44:23 = 15 сент. =head3 MMMEd (E MMM d) 2008-02-05T18:30:30 = Вт февр. 5 1995-12-22T09:05:02 = Пт дек. 22 -0010-09-15T04:44:23 = Сб сент. 15 =head3 MMMMd (d MMMM) 2008-02-05T18:30:30 = 5 февраля 1995-12-22T09:05:02 = 22 декабря -0010-09-15T04:44:23 = 15 сентября =head3 MMMMEd (E MMMM d) 2008-02-05T18:30:30 = Вт февраля 5 1995-12-22T09:05:02 = Пт декабря 22 -0010-09-15T04:44:23 = Сб сентября 15 =head3 mmss (mm:ss) 2008-02-05T18:30:30 = 30:30 1995-12-22T09:05:02 = 05:02 -0010-09-15T04:44:23 = 44:23 =head3 ms (mm:ss) 2008-02-05T18:30:30 = 30:30 1995-12-22T09:05:02 = 05:02 -0010-09-15T04:44:23 = 44:23 =head3 y (y) 2008-02-05T18:30:30 = 2008 1995-12-22T09:05:02 = 1995 -0010-09-15T04:44:23 = -10 =head3 yM (yyyy-M) 2008-02-05T18:30:30 = 2008-2 1995-12-22T09:05:02 = 1995-12 -0010-09-15T04:44:23 = -010-9 =head3 yMEd (EEE, yyyy-M-d) 2008-02-05T18:30:30 = Вт, 2008-2-5 1995-12-22T09:05:02 = Пт, 1995-12-22 -0010-09-15T04:44:23 = Сб, -010-9-15 =head3 yMMM (MMM y) 2008-02-05T18:30:30 = февр. 2008 1995-12-22T09:05:02 = дек. 1995 -0010-09-15T04:44:23 = сент. -10 =head3 yMMMEd (E, d MMM y) 2008-02-05T18:30:30 = Вт, 5 февр. 2008 1995-12-22T09:05:02 = Пт, 22 дек. 1995 -0010-09-15T04:44:23 = Сб, 15 сент. -10 =head3 yMMMM (MMMM y) 2008-02-05T18:30:30 = февраля 2008 1995-12-22T09:05:02 = декабря 1995 -0010-09-15T04:44:23 = сентября -10 =head3 yQ (Q y) 2008-02-05T18:30:30 = 1 2008 1995-12-22T09:05:02 = 4 1995 -0010-09-15T04:44:23 = 3 -10 =head3 yQQQ (y QQQ) 2008-02-05T18:30:30 = 2008 1-й кв. 1995-12-22T09:05:02 = 1995 4-й кв. -0010-09-15T04:44:23 = -10 3-й кв. =head3 yyMM (MM.yy) 2008-02-05T18:30:30 = 02.08 1995-12-22T09:05:02 = 12.95 -0010-09-15T04:44:23 = 09.-10 =head3 yyMMM (MMM yy) 2008-02-05T18:30:30 = февр. 08 1995-12-22T09:05:02 = дек. 95 -0010-09-15T04:44:23 = сент. -10 =head3 yyMMMEEEd (EEE, d MMM yy) 2008-02-05T18:30:30 = Вт, 5 февр. 08 1995-12-22T09:05:02 = Пт, 22 дек. 95 -0010-09-15T04:44:23 = Сб, 15 сент. -10 =head3 yyQ (Q yy) 2008-02-05T18:30:30 = 1 08 1995-12-22T09:05:02 = 4 95 -0010-09-15T04:44:23 = 3 -10 =head3 yyyy (y) 2008-02-05T18:30:30 = 2008 1995-12-22T09:05:02 = 1995 -0010-09-15T04:44:23 = -10 =head3 yyyyLLLL (LLLL y) 2008-02-05T18:30:30 = Февраль 2008 1995-12-22T09:05:02 = Декабрь 1995 -0010-09-15T04:44:23 = Сентябрь -10 =head3 yyyyMM (MM.yyyy) 2008-02-05T18:30:30 = 02.2008 1995-12-22T09:05:02 = 12.1995 -0010-09-15T04:44:23 = 09.-010 =head3 yyyyMMMM (MMMM y) 2008-02-05T18:30:30 = февраля 2008 1995-12-22T09:05:02 = декабря 1995 -0010-09-15T04:44:23 = сентября -10 =head3 yyyyQQQQ (QQQQ y 'г'.) 2008-02-05T18:30:30 = 1-й квартал 2008 г. 1995-12-22T09:05:02 = 4-й квартал 1995 г. -0010-09-15T04:44:23 = 3-й квартал -10 г. =head2 Miscellaneous =head3 Prefers 24 hour time? Yes =head3 Local first day of the week понедельник =head1 SUPPORT See L<DateTime::Locale>. =head1 AUTHOR Dave Rolsky <autarch@urth.org> =head1 COPYRIGHT Copyright (c) 2008 David Rolsky. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. This module was generated from data provided by the CLDR project, see the LICENSE.cldr in this distribution for details on the CLDR data's license. =cut
liuyangning/WX_web
xampp/perl/vendor/lib/DateTime/Locale/ru_RU.pm
Perl
mit
11,756
=head1 NAME X<function> perlfunc - Perl builtin functions =head1 DESCRIPTION The functions in this section can serve as terms in an expression. They fall into two major categories: list operators and named unary operators. These differ in their precedence relationship with a following comma. (See the precedence table in L<perlop>.) List operators take more than one argument, while unary operators can never take more than one argument. Thus, a comma terminates the argument of a unary operator, but merely separates the arguments of a list operator. A unary operator generally provides scalar context to its argument, while a list operator may provide either scalar or list contexts for its arguments. If it does both, scalar arguments come first and list argument follow, and there can only ever be one such list argument. For instance, splice() has three scalar arguments followed by a list, whereas gethostbyname() has four scalar arguments. In the syntax descriptions that follow, list operators that expect a list (and provide list context for elements of the list) are shown with LIST as an argument. Such a list may consist of any combination of scalar arguments or list values; the list values will be included in the list as if each individual element were interpolated at that point in the list, forming a longer single-dimensional list value. Commas should separate literal elements of the LIST. Any function in the list below may be used either with or without parentheses around its arguments. (The syntax descriptions omit the parentheses.) If you use parentheses, the simple but occasionally surprising rule is this: It I<looks> like a function, therefore it I<is> a function, and precedence doesn't matter. Otherwise it's a list operator or unary operator, and precedence does matter. Whitespace between the function and left parenthesis doesn't count, so sometimes you need to be careful: print 1+2+4; # Prints 7. print(1+2) + 4; # Prints 3. print (1+2)+4; # Also prints 3! print +(1+2)+4; # Prints 7. print ((1+2)+4); # Prints 7. If you run Perl with the B<-w> switch it can warn you about this. For example, the third line above produces: print (...) interpreted as function at - line 1. Useless use of integer addition in void context at - line 1. A few functions take no arguments at all, and therefore work as neither unary nor list operators. These include such functions as C<time> and C<endpwent>. For example, C<time+86_400> always means C<time() + 86_400>. For functions that can be used in either a scalar or list context, nonabortive failure is generally indicated in scalar context by returning the undefined value, and in list context by returning the empty list. Remember the following important rule: There is B<no rule> that relates the behavior of an expression in list context to its behavior in scalar context, or vice versa. It might do two totally different things. Each operator and function decides which sort of value would be most appropriate to return in scalar context. Some operators return the length of the list that would have been returned in list context. Some operators return the first value in the list. Some operators return the last value in the list. Some operators return a count of successful operations. In general, they do what you want, unless you want consistency. X<context> A named array in scalar context is quite different from what would at first glance appear to be a list in scalar context. You can't get a list like C<(1,2,3)> into being in scalar context, because the compiler knows the context at compile time. It would generate the scalar comma operator there, not the list construction version of the comma. That means it was never a list to start with. In general, functions in Perl that serve as wrappers for system calls ("syscalls") of the same name (like chown(2), fork(2), closedir(2), etc.) return true when they succeed and C<undef> otherwise, as is usually mentioned in the descriptions below. This is different from the C interfaces, which return C<-1> on failure. Exceptions to this rule include C<wait>, C<waitpid>, and C<syscall>. System calls also set the special C<$!> variable on failure. Other functions do not, except accidentally. Extension modules can also hook into the Perl parser to define new kinds of keyword-headed expression. These may look like functions, but may also look completely different. The syntax following the keyword is defined entirely by the extension. If you are an implementor, see L<perlapi/PL_keyword_plugin> for the mechanism. If you are using such a module, see the module's documentation for details of the syntax that it defines. =head2 Perl Functions by Category X<function> Here are Perl's functions (including things that look like functions, like some keywords and named operators) arranged by category. Some functions appear in more than one place. =over 4 =item Functions for SCALARs or strings X<scalar> X<string> X<character> =for Pod::Functions =String C<chomp>, C<chop>, C<chr>, C<crypt>, C<fc>, C<hex>, C<index>, C<lc>, C<lcfirst>, C<length>, C<oct>, C<ord>, C<pack>, C<q//>, C<qq//>, C<reverse>, C<rindex>, C<sprintf>, C<substr>, C<tr///>, C<uc>, C<ucfirst>, C<y///> C<fc> is available only if the C<"fc"> feature is enabled or if it is prefixed with C<CORE::>. The C<"fc"> feature is enabled automatically with a C<use v5.16> (or higher) declaration in the current scope. =item Regular expressions and pattern matching X<regular expression> X<regex> X<regexp> =for Pod::Functions =Regexp C<m//>, C<pos>, C<qr//>, C<quotemeta>, C<s///>, C<split>, C<study> =item Numeric functions X<numeric> X<number> X<trigonometric> X<trigonometry> =for Pod::Functions =Math C<abs>, C<atan2>, C<cos>, C<exp>, C<hex>, C<int>, C<log>, C<oct>, C<rand>, C<sin>, C<sqrt>, C<srand> =item Functions for real @ARRAYs X<array> =for Pod::Functions =ARRAY C<each>, C<keys>, C<pop>, C<push>, C<shift>, C<splice>, C<unshift>, C<values> =item Functions for list data X<list> =for Pod::Functions =LIST C<grep>, C<join>, C<map>, C<qw//>, C<reverse>, C<sort>, C<unpack> =item Functions for real %HASHes X<hash> =for Pod::Functions =HASH C<delete>, C<each>, C<exists>, C<keys>, C<values> =item Input and output functions X<I/O> X<input> X<output> X<dbm> =for Pod::Functions =I/O C<binmode>, C<close>, C<closedir>, C<dbmclose>, C<dbmopen>, C<die>, C<eof>, C<fileno>, C<flock>, C<format>, C<getc>, C<print>, C<printf>, C<read>, C<readdir>, C<readline> C<rewinddir>, C<say>, C<seek>, C<seekdir>, C<select>, C<syscall>, C<sysread>, C<sysseek>, C<syswrite>, C<tell>, C<telldir>, C<truncate>, C<warn>, C<write> C<say> is available only if the C<"say"> feature is enabled or if it is prefixed with C<CORE::>. The C<"say"> feature is enabled automatically with a C<use v5.10> (or higher) declaration in the current scope. =item Functions for fixed-length data or records =for Pod::Functions =Binary C<pack>, C<read>, C<syscall>, C<sysread>, C<sysseek>, C<syswrite>, C<unpack>, C<vec> =item Functions for filehandles, files, or directories X<file> X<filehandle> X<directory> X<pipe> X<link> X<symlink> =for Pod::Functions =File C<-I<X>>, C<chdir>, C<chmod>, C<chown>, C<chroot>, C<fcntl>, C<glob>, C<ioctl>, C<link>, C<lstat>, C<mkdir>, C<open>, C<opendir>, C<readlink>, C<rename>, C<rmdir>, C<stat>, C<symlink>, C<sysopen>, C<umask>, C<unlink>, C<utime> =item Keywords related to the control flow of your Perl program X<control flow> =for Pod::Functions =Flow C<break>, C<caller>, C<continue>, C<die>, C<do>, C<dump>, C<eval>, C<evalbytes> C<exit>, C<__FILE__>, C<goto>, C<last>, C<__LINE__>, C<next>, C<__PACKAGE__>, C<redo>, C<return>, C<sub>, C<__SUB__>, C<wantarray> C<break> is available only if you enable the experimental C<"switch"> feature or use the C<CORE::> prefix. The C<"switch"> feature also enables the C<default>, C<given> and C<when> statements, which are documented in L<perlsyn/"Switch Statements">. The C<"switch"> feature is enabled automatically with a C<use v5.10> (or higher) declaration in the current scope. In Perl v5.14 and earlier, C<continue> required the C<"switch"> feature, like the other keywords. C<evalbytes> is only available with with the C<"evalbytes"> feature (see L<feature>) or if prefixed with C<CORE::>. C<__SUB__> is only available with with the C<"current_sub"> feature or if prefixed with C<CORE::>. Both the C<"evalbytes"> and C<"current_sub"> features are enabled automatically with a C<use v5.16> (or higher) declaration in the current scope. =item Keywords related to scoping =for Pod::Functions =Namespace C<caller>, C<import>, C<local>, C<my>, C<our>, C<package>, C<state>, C<use> C<state> is available only if the C<"state"> feature is enabled or if it is prefixed with C<CORE::>. The C<"state"> feature is enabled automatically with a C<use v5.10> (or higher) declaration in the current scope. =item Miscellaneous functions =for Pod::Functions =Misc C<defined>, C<formline>, C<lock>, C<prototype>, C<reset>, C<scalar>, C<undef> =item Functions for processes and process groups X<process> X<pid> X<process id> =for Pod::Functions =Process C<alarm>, C<exec>, C<fork>, C<getpgrp>, C<getppid>, C<getpriority>, C<kill>, C<pipe>, C<qx//>, C<readpipe>, C<setpgrp>, C<setpriority>, C<sleep>, C<system>, C<times>, C<wait>, C<waitpid> =item Keywords related to Perl modules X<module> =for Pod::Functions =Modules C<do>, C<import>, C<no>, C<package>, C<require>, C<use> =item Keywords related to classes and object-orientation X<object> X<class> X<package> =for Pod::Functions =Objects C<bless>, C<dbmclose>, C<dbmopen>, C<package>, C<ref>, C<tie>, C<tied>, C<untie>, C<use> =item Low-level socket functions X<socket> X<sock> =for Pod::Functions =Socket C<accept>, C<bind>, C<connect>, C<getpeername>, C<getsockname>, C<getsockopt>, C<listen>, C<recv>, C<send>, C<setsockopt>, C<shutdown>, C<socket>, C<socketpair> =item System V interprocess communication functions X<IPC> X<System V> X<semaphore> X<shared memory> X<memory> X<message> =for Pod::Functions =SysV C<msgctl>, C<msgget>, C<msgrcv>, C<msgsnd>, C<semctl>, C<semget>, C<semop>, C<shmctl>, C<shmget>, C<shmread>, C<shmwrite> =item Fetching user and group info X<user> X<group> X<password> X<uid> X<gid> X<passwd> X</etc/passwd> =for Pod::Functions =User C<endgrent>, C<endhostent>, C<endnetent>, C<endpwent>, C<getgrent>, C<getgrgid>, C<getgrnam>, C<getlogin>, C<getpwent>, C<getpwnam>, C<getpwuid>, C<setgrent>, C<setpwent> =item Fetching network info X<network> X<protocol> X<host> X<hostname> X<IP> X<address> X<service> =for Pod::Functions =Network C<endprotoent>, C<endservent>, C<gethostbyaddr>, C<gethostbyname>, C<gethostent>, C<getnetbyaddr>, C<getnetbyname>, C<getnetent>, C<getprotobyname>, C<getprotobynumber>, C<getprotoent>, C<getservbyname>, C<getservbyport>, C<getservent>, C<sethostent>, C<setnetent>, C<setprotoent>, C<setservent> =item Time-related functions X<time> X<date> =for Pod::Functions =Time C<gmtime>, C<localtime>, C<time>, C<times> =item Non-function keywords =for Pod::Functions =!Non-functions C<and>, C<AUTOLOAD>, C<BEGIN>, C<CHECK>, C<cmp>, C<CORE>, C<__DATA__>, C<default>, C<DESTROY>, C<else>, C<elseif>, C<elsif>, C<END>, C<__END__>, C<eq>, C<for>, C<foreach>, C<ge>, C<given>, C<gt>, C<if>, C<INIT>, C<le>, C<lt>, C<ne>, C<not>, C<or>, C<UNITCHECK>, C<unless>, C<until>, C<when>, C<while>, C<x>, C<xor> =back =head2 Portability X<portability> X<Unix> X<portable> Perl was born in Unix and can therefore access all common Unix system calls. In non-Unix environments, the functionality of some Unix system calls may not be available or details of the available functionality may differ slightly. The Perl functions affected by this are: C<-X>, C<binmode>, C<chmod>, C<chown>, C<chroot>, C<crypt>, C<dbmclose>, C<dbmopen>, C<dump>, C<endgrent>, C<endhostent>, C<endnetent>, C<endprotoent>, C<endpwent>, C<endservent>, C<exec>, C<fcntl>, C<flock>, C<fork>, C<getgrent>, C<getgrgid>, C<gethostbyname>, C<gethostent>, C<getlogin>, C<getnetbyaddr>, C<getnetbyname>, C<getnetent>, C<getppid>, C<getpgrp>, C<getpriority>, C<getprotobynumber>, C<getprotoent>, C<getpwent>, C<getpwnam>, C<getpwuid>, C<getservbyport>, C<getservent>, C<getsockopt>, C<glob>, C<ioctl>, C<kill>, C<link>, C<lstat>, C<msgctl>, C<msgget>, C<msgrcv>, C<msgsnd>, C<open>, C<pipe>, C<readlink>, C<rename>, C<select>, C<semctl>, C<semget>, C<semop>, C<setgrent>, C<sethostent>, C<setnetent>, C<setpgrp>, C<setpriority>, C<setprotoent>, C<setpwent>, C<setservent>, C<setsockopt>, C<shmctl>, C<shmget>, C<shmread>, C<shmwrite>, C<socket>, C<socketpair>, C<stat>, C<symlink>, C<syscall>, C<sysopen>, C<system>, C<times>, C<truncate>, C<umask>, C<unlink>, C<utime>, C<wait>, C<waitpid> For more information about the portability of these functions, see L<perlport> and other available platform-specific documentation. =head2 Alphabetical Listing of Perl Functions =over =item -X FILEHANDLE X<-r>X<-w>X<-x>X<-o>X<-R>X<-W>X<-X>X<-O>X<-e>X<-z>X<-s>X<-f>X<-d>X<-l>X<-p> X<-S>X<-b>X<-c>X<-t>X<-u>X<-g>X<-k>X<-T>X<-B>X<-M>X<-A>X<-C> =item -X EXPR =item -X DIRHANDLE =item -X =for Pod::Functions a file test (-r, -x, etc) A file test, where X is one of the letters listed below. This unary operator takes one argument, either a filename, a filehandle, or a dirhandle, and tests the associated file to see if something is true about it. If the argument is omitted, tests C<$_>, except for C<-t>, which tests STDIN. Unless otherwise documented, it returns C<1> for true and C<''> for false, or the undefined value if the file doesn't exist. Despite the funny names, precedence is the same as any other named unary operator. The operator may be any of: -r File is readable by effective uid/gid. -w File is writable by effective uid/gid. -x File is executable by effective uid/gid. -o File is owned by effective uid. -R File is readable by real uid/gid. -W File is writable by real uid/gid. -X File is executable by real uid/gid. -O File is owned by real uid. -e File exists. -z File has zero size (is empty). -s File has nonzero size (returns size in bytes). -f File is a plain file. -d File is a directory. -l File is a symbolic link. -p File is a named pipe (FIFO), or Filehandle is a pipe. -S File is a socket. -b File is a block special file. -c File is a character special file. -t Filehandle is opened to a tty. -u File has setuid bit set. -g File has setgid bit set. -k File has sticky bit set. -T File is an ASCII text file (heuristic guess). -B File is a "binary" file (opposite of -T). -M Script start time minus file modification time, in days. -A Same for access time. -C Same for inode change time (Unix, may differ for other platforms) Example: while (<>) { chomp; next unless -f $_; # ignore specials #... } Note that C<-s/a/b/> does not do a negated substitution. Saying C<-exp($foo)> still works as expected, however: only single letters following a minus are interpreted as file tests. These operators are exempt from the "looks like a function rule" described above. That is, an opening parenthesis after the operator does not affect how much of the following code constitutes the argument. Put the opening parentheses before the operator to separate it from code that follows (this applies only to operators with higher precedence than unary operators, of course): -s($file) + 1024 # probably wrong; same as -s($file + 1024) (-s $file) + 1024 # correct The interpretation of the file permission operators C<-r>, C<-R>, C<-w>, C<-W>, C<-x>, and C<-X> is by default based solely on the mode of the file and the uids and gids of the user. There may be other reasons you can't actually read, write, or execute the file: for example network filesystem access controls, ACLs (access control lists), read-only filesystems, and unrecognized executable formats. Note that the use of these six specific operators to verify if some operation is possible is usually a mistake, because it may be open to race conditions. Also note that, for the superuser on the local filesystems, the C<-r>, C<-R>, C<-w>, and C<-W> tests always return 1, and C<-x> and C<-X> return 1 if any execute bit is set in the mode. Scripts run by the superuser may thus need to do a stat() to determine the actual mode of the file, or temporarily set their effective uid to something else. If you are using ACLs, there is a pragma called C<filetest> that may produce more accurate results than the bare stat() mode bits. When under C<use filetest 'access'> the above-mentioned filetests test whether the permission can(not) be granted using the access(2) family of system calls. Also note that the C<-x> and C<-X> may under this pragma return true even if there are no execute permission bits set (nor any extra execute permission ACLs). This strangeness is due to the underlying system calls' definitions. Note also that, due to the implementation of C<use filetest 'access'>, the C<_> special filehandle won't cache the results of the file tests when this pragma is in effect. Read the documentation for the C<filetest> pragma for more information. The C<-T> and C<-B> switches work as follows. The first block or so of the file is examined for odd characters such as strange control codes or characters with the high bit set. If too many strange characters (>30%) are found, it's a C<-B> file; otherwise it's a C<-T> file. Also, any file containing a zero byte in the first block is considered a binary file. If C<-T> or C<-B> is used on a filehandle, the current IO buffer is examined rather than the first block. Both C<-T> and C<-B> return true on an empty file, or a file at EOF when testing a filehandle. Because you have to read a file to do the C<-T> test, on most occasions you want to use a C<-f> against the file first, as in C<next unless -f $file && -T $file>. If any of the file tests (or either the C<stat> or C<lstat> operator) is given the special filehandle consisting of a solitary underline, then the stat structure of the previous file test (or stat operator) is used, saving a system call. (This doesn't work with C<-t>, and you need to remember that lstat() and C<-l> leave values in the stat structure for the symbolic link, not the real file.) (Also, if the stat buffer was filled by an C<lstat> call, C<-T> and C<-B> will reset it with the results of C<stat _>). Example: print "Can do.\n" if -r $a || -w _ || -x _; stat($filename); print "Readable\n" if -r _; print "Writable\n" if -w _; print "Executable\n" if -x _; print "Setuid\n" if -u _; print "Setgid\n" if -g _; print "Sticky\n" if -k _; print "Text\n" if -T _; print "Binary\n" if -B _; As of Perl 5.9.1, as a form of purely syntactic sugar, you can stack file test operators, in a way that C<-f -w -x $file> is equivalent to C<-x $file && -w _ && -f _>. (This is only fancy fancy: if you use the return value of C<-f $file> as an argument to another filetest operator, no special magic will happen.) Portability issues: L<perlport/-X>. To avoid confusing would-be users of your code with mysterious syntax errors, put something like this at the top of your script: use 5.010; # so filetest ops can stack =item abs VALUE X<abs> X<absolute> =item abs =for Pod::Functions absolute value function Returns the absolute value of its argument. If VALUE is omitted, uses C<$_>. =item accept NEWSOCKET,GENERICSOCKET X<accept> =for Pod::Functions accept an incoming socket connect Accepts an incoming socket connect, just as accept(2) does. Returns the packed address if it succeeded, false otherwise. See the example in L<perlipc/"Sockets: Client/Server Communication">. On systems that support a close-on-exec flag on files, the flag will be set for the newly opened file descriptor, as determined by the value of $^F. See L<perlvar/$^F>. =item alarm SECONDS X<alarm> X<SIGALRM> X<timer> =item alarm =for Pod::Functions schedule a SIGALRM Arranges to have a SIGALRM delivered to this process after the specified number of wallclock seconds has elapsed. If SECONDS is not specified, the value stored in C<$_> is used. (On some machines, unfortunately, the elapsed time may be up to one second less or more than you specified because of how seconds are counted, and process scheduling may delay the delivery of the signal even further.) Only one timer may be counting at once. Each call disables the previous timer, and an argument of C<0> may be supplied to cancel the previous timer without starting a new one. The returned value is the amount of time remaining on the previous timer. For delays of finer granularity than one second, the Time::HiRes module (from CPAN, and starting from Perl 5.8 part of the standard distribution) provides ualarm(). You may also use Perl's four-argument version of select() leaving the first three arguments undefined, or you might be able to use the C<syscall> interface to access setitimer(2) if your system supports it. See L<perlfaq8> for details. It is usually a mistake to intermix C<alarm> and C<sleep> calls, because C<sleep> may be internally implemented on your system with C<alarm>. If you want to use C<alarm> to time out a system call you need to use an C<eval>/C<die> pair. You can't rely on the alarm causing the system call to fail with C<$!> set to C<EINTR> because Perl sets up signal handlers to restart system calls on some systems. Using C<eval>/C<die> always works, modulo the caveats given in L<perlipc/"Signals">. eval { local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required alarm $timeout; $nread = sysread SOCKET, $buffer, $size; alarm 0; }; if ($@) { die unless $@ eq "alarm\n"; # propagate unexpected errors # timed out } else { # didn't } For more information see L<perlipc>. Portability issues: L<perlport/alarm>. =item atan2 Y,X X<atan2> X<arctangent> X<tan> X<tangent> =for Pod::Functions arctangent of Y/X in the range -PI to PI Returns the arctangent of Y/X in the range -PI to PI. For the tangent operation, you may use the C<Math::Trig::tan> function, or use the familiar relation: sub tan { sin($_[0]) / cos($_[0]) } The return value for C<atan2(0,0)> is implementation-defined; consult your atan2(3) manpage for more information. Portability issues: L<perlport/atan2>. =item bind SOCKET,NAME X<bind> =for Pod::Functions binds an address to a socket Binds a network address to a socket, just as bind(2) does. Returns true if it succeeded, false otherwise. NAME should be a packed address of the appropriate type for the socket. See the examples in L<perlipc/"Sockets: Client/Server Communication">. =item binmode FILEHANDLE, LAYER X<binmode> X<binary> X<text> X<DOS> X<Windows> =item binmode FILEHANDLE =for Pod::Functions prepare binary files for I/O Arranges for FILEHANDLE to be read or written in "binary" or "text" mode on systems where the run-time libraries distinguish between binary and text files. If FILEHANDLE is an expression, the value is taken as the name of the filehandle. Returns true on success, otherwise it returns C<undef> and sets C<$!> (errno). On some systems (in general, DOS- and Windows-based systems) binmode() is necessary when you're not working with a text file. For the sake of portability it is a good idea always to use it when appropriate, and never to use it when it isn't appropriate. Also, people can set their I/O to be by default UTF8-encoded Unicode, not bytes. In other words: regardless of platform, use binmode() on binary data, like images, for example. If LAYER is present it is a single string, but may contain multiple directives. The directives alter the behaviour of the filehandle. When LAYER is present, using binmode on a text file makes sense. If LAYER is omitted or specified as C<:raw> the filehandle is made suitable for passing binary data. This includes turning off possible CRLF translation and marking it as bytes (as opposed to Unicode characters). Note that, despite what may be implied in I<"Programming Perl"> (the Camel, 3rd edition) or elsewhere, C<:raw> is I<not> simply the inverse of C<:crlf>. Other layers that would affect the binary nature of the stream are I<also> disabled. See L<PerlIO>, L<perlrun>, and the discussion about the PERLIO environment variable. The C<:bytes>, C<:crlf>, C<:utf8>, and any other directives of the form C<:...>, are called I/O I<layers>. The C<open> pragma can be used to establish default I/O layers. See L<open>. I<The LAYER parameter of the binmode() function is described as "DISCIPLINE" in "Programming Perl, 3rd Edition". However, since the publishing of this book, by many known as "Camel III", the consensus of the naming of this functionality has moved from "discipline" to "layer". All documentation of this version of Perl therefore refers to "layers" rather than to "disciplines". Now back to the regularly scheduled documentation...> To mark FILEHANDLE as UTF-8, use C<:utf8> or C<:encoding(UTF-8)>. C<:utf8> just marks the data as UTF-8 without further checking, while C<:encoding(UTF-8)> checks the data for actually being valid UTF-8. More details can be found in L<PerlIO::encoding>. In general, binmode() should be called after open() but before any I/O is done on the filehandle. Calling binmode() normally flushes any pending buffered output data (and perhaps pending input data) on the handle. An exception to this is the C<:encoding> layer that changes the default character encoding of the handle; see L</open>. The C<:encoding> layer sometimes needs to be called in mid-stream, and it doesn't flush the stream. The C<:encoding> also implicitly pushes on top of itself the C<:utf8> layer because internally Perl operates on UTF8-encoded Unicode characters. The operating system, device drivers, C libraries, and Perl run-time system all conspire to let the programmer treat a single character (C<\n>) as the line terminator, irrespective of external representation. On many operating systems, the native text file representation matches the internal representation, but on some platforms the external representation of C<\n> is made up of more than one character. All variants of Unix, Mac OS (old and new), and Stream_LF files on VMS use a single character to end each line in the external representation of text (even though that single character is CARRIAGE RETURN on old, pre-Darwin flavors of Mac OS, and is LINE FEED on Unix and most VMS files). In other systems like OS/2, DOS, and the various flavors of MS-Windows, your program sees a C<\n> as a simple C<\cJ>, but what's stored in text files are the two characters C<\cM\cJ>. That means that if you don't use binmode() on these systems, C<\cM\cJ> sequences on disk will be converted to C<\n> on input, and any C<\n> in your program will be converted back to C<\cM\cJ> on output. This is what you want for text files, but it can be disastrous for binary files. Another consequence of using binmode() (on some systems) is that special end-of-file markers will be seen as part of the data stream. For systems from the Microsoft family this means that, if your binary data contain C<\cZ>, the I/O subsystem will regard it as the end of the file, unless you use binmode(). binmode() is important not only for readline() and print() operations, but also when using read(), seek(), sysread(), syswrite() and tell() (see L<perlport> for more details). See the C<$/> and C<$\> variables in L<perlvar> for how to manually set your input and output line-termination sequences. Portability issues: L<perlport/binmode>. =item bless REF,CLASSNAME X<bless> =item bless REF =for Pod::Functions create an object This function tells the thingy referenced by REF that it is now an object in the CLASSNAME package. If CLASSNAME is omitted, the current package is used. Because a C<bless> is often the last thing in a constructor, it returns the reference for convenience. Always use the two-argument version if a derived class might inherit the function doing the blessing. SeeL<perlobj> for more about the blessing (and blessings) of objects. Consider always blessing objects in CLASSNAMEs that are mixed case. Namespaces with all lowercase names are considered reserved for Perl pragmata. Builtin types have all uppercase names. To prevent confusion, you may wish to avoid such package names as well. Make sure that CLASSNAME is a true value. See L<perlmod/"Perl Modules">. =item break =for Pod::Functions +switch break out of a C<given> block Break out of a C<given()> block. This keyword is enabled by the C<"switch"> feature: see L<feature> for more information. You can also access it by prefixing it with C<CORE::>. Alternately, include a C<use v5.10> or later to the current scope. =item caller EXPR X<caller> X<call stack> X<stack> X<stack trace> =item caller =for Pod::Functions get context of the current subroutine call Returns the context of the current subroutine call. In scalar context, returns the caller's package name if there I<is> a caller (that is, if we're in a subroutine or C<eval> or C<require>) and the undefined value otherwise. In list context, returns # 0 1 2 ($package, $filename, $line) = caller; With EXPR, it returns some extra information that the debugger uses to print a stack trace. The value of EXPR indicates how many call frames to go back before the current one. # 0 1 2 3 4 ($package, $filename, $line, $subroutine, $hasargs, # 5 6 7 8 9 10 $wantarray, $evaltext, $is_require, $hints, $bitmask, $hinthash) = caller($i); Here $subroutine may be C<(eval)> if the frame is not a subroutine call, but an C<eval>. In such a case additional elements $evaltext and C<$is_require> are set: C<$is_require> is true if the frame is created by a C<require> or C<use> statement, $evaltext contains the text of the C<eval EXPR> statement. In particular, for an C<eval BLOCK> statement, $subroutine is C<(eval)>, but $evaltext is undefined. (Note also that each C<use> statement creates a C<require> frame inside an C<eval EXPR> frame.) $subroutine may also be C<(unknown)> if this particular subroutine happens to have been deleted from the symbol table. C<$hasargs> is true if a new instance of C<@_> was set up for the frame. C<$hints> and C<$bitmask> contain pragmatic hints that the caller was compiled with. The C<$hints> and C<$bitmask> values are subject to change between versions of Perl, and are not meant for external use. C<$hinthash> is a reference to a hash containing the value of C<%^H> when the caller was compiled, or C<undef> if C<%^H> was empty. Do not modify the values of this hash, as they are the actual values stored in the optree. Furthermore, when called from within the DB package in list context, and with an argument, caller returns more detailed information: it sets the list variable C<@DB::args> to be the arguments with which the subroutine was invoked. Be aware that the optimizer might have optimized call frames away before C<caller> had a chance to get the information. That means that C<caller(N)> might not return information about the call frame you expect it to, for C<< N > 1 >>. In particular, C<@DB::args> might have information from the previous time C<caller> was called. Be aware that setting C<@DB::args> is I<best effort>, intended for debugging or generating backtraces, and should not be relied upon. In particular, as C<@_> contains aliases to the caller's arguments, Perl does not take a copy of C<@_>, so C<@DB::args> will contain modifications the subroutine makes to C<@_> or its contents, not the original values at call time. C<@DB::args>, like C<@_>, does not hold explicit references to its elements, so under certain cases its elements may have become freed and reallocated for other variables or temporary values. Finally, a side effect of the current implementation is that the effects of C<shift @_> can I<normally> be undone (but not C<pop @_> or other splicing, I<and> not if a reference to C<@_> has been taken, I<and> subject to the caveat about reallocated elements), so C<@DB::args> is actually a hybrid of the current state and initial state of C<@_>. Buyer beware. =item chdir EXPR X<chdir> X<cd> X<directory, change> =item chdir FILEHANDLE =item chdir DIRHANDLE =item chdir =for Pod::Functions change your current working directory Changes the working directory to EXPR, if possible. If EXPR is omitted, changes to the directory specified by C<$ENV{HOME}>, if set; if not, changes to the directory specified by C<$ENV{LOGDIR}>. (Under VMS, the variable C<$ENV{SYS$LOGIN}> is also checked, and used if it is set.) If neither is set, C<chdir> does nothing. It returns true on success, false otherwise. See the example under C<die>. On systems that support fchdir(2), you may pass a filehandle or directory handle as the argument. On systems that don't support fchdir(2), passing handles raises an exception. =item chmod LIST X<chmod> X<permission> X<mode> =for Pod::Functions changes the permissions on a list of files Changes the permissions of a list of files. The first element of the list must be the numeric mode, which should probably be an octal number, and which definitely should I<not> be a string of octal digits: C<0644> is okay, but C<"0644"> is not. Returns the number of files successfully changed. See also L</oct> if all you have is a string. $cnt = chmod 0755, "foo", "bar"; chmod 0755, @executables; $mode = "0644"; chmod $mode, "foo"; # !!! sets mode to # --w----r-T $mode = "0644"; chmod oct($mode), "foo"; # this is better $mode = 0644; chmod $mode, "foo"; # this is best On systems that support fchmod(2), you may pass filehandles among the files. On systems that don't support fchmod(2), passing filehandles raises an exception. Filehandles must be passed as globs or glob references to be recognized; barewords are considered filenames. open(my $fh, "<", "foo"); my $perm = (stat $fh)[2] & 07777; chmod($perm | 0600, $fh); You can also import the symbolic C<S_I*> constants from the C<Fcntl> module: use Fcntl qw( :mode ); chmod S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH, @executables; # Identical to the chmod 0755 of the example above. Portability issues: L<perlport/chmod>. =item chomp VARIABLE X<chomp> X<INPUT_RECORD_SEPARATOR> X<$/> X<newline> X<eol> =item chomp( LIST ) =item chomp =for Pod::Functions remove a trailing record separator from a string This safer version of L</chop> removes any trailing string that corresponds to the current value of C<$/> (also known as $INPUT_RECORD_SEPARATOR in the C<English> module). It returns the total number of characters removed from all its arguments. It's often used to remove the newline from the end of an input record when you're worried that the final record may be missing its newline. When in paragraph mode (C<$/ = "">), it removes all trailing newlines from the string. When in slurp mode (C<$/ = undef>) or fixed-length record mode (C<$/> is a reference to an integer or the like; see L<perlvar>) chomp() won't remove anything. If VARIABLE is omitted, it chomps C<$_>. Example: while (<>) { chomp; # avoid \n on last field @array = split(/:/); # ... } If VARIABLE is a hash, it chomps the hash's values, but not its keys. You can actually chomp anything that's an lvalue, including an assignment: chomp($cwd = `pwd`); chomp($answer = <STDIN>); If you chomp a list, each element is chomped, and the total number of characters removed is returned. Note that parentheses are necessary when you're chomping anything that is not a simple variable. This is because C<chomp $cwd = `pwd`;> is interpreted as C<(chomp $cwd) = `pwd`;>, rather than as C<chomp( $cwd = `pwd` )> which you might expect. Similarly, C<chomp $a, $b> is interpreted as C<chomp($a), $b> rather than as C<chomp($a, $b)>. =item chop VARIABLE X<chop> =item chop( LIST ) =item chop =for Pod::Functions remove the last character from a string Chops off the last character of a string and returns the character chopped. It is much more efficient than C<s/.$//s> because it neither scans nor copies the string. If VARIABLE is omitted, chops C<$_>. If VARIABLE is a hash, it chops the hash's values, but not its keys. You can actually chop anything that's an lvalue, including an assignment. If you chop a list, each element is chopped. Only the value of the last C<chop> is returned. Note that C<chop> returns the last character. To return all but the last character, use C<substr($string, 0, -1)>. See also L</chomp>. =item chown LIST X<chown> X<owner> X<user> X<group> =for Pod::Functions change the ownership on a list of files Changes the owner (and group) of a list of files. The first two elements of the list must be the I<numeric> uid and gid, in that order. A value of -1 in either position is interpreted by most systems to leave that value unchanged. Returns the number of files successfully changed. $cnt = chown $uid, $gid, 'foo', 'bar'; chown $uid, $gid, @filenames; On systems that support fchown(2), you may pass filehandles among the files. On systems that don't support fchown(2), passing filehandles raises an exception. Filehandles must be passed as globs or glob references to be recognized; barewords are considered filenames. Here's an example that looks up nonnumeric uids in the passwd file: print "User: "; chomp($user = <STDIN>); print "Files: "; chomp($pattern = <STDIN>); ($login,$pass,$uid,$gid) = getpwnam($user) or die "$user not in passwd file"; @ary = glob($pattern); # expand filenames chown $uid, $gid, @ary; On most systems, you are not allowed to change the ownership of the file unless you're the superuser, although you should be able to change the group to any of your secondary groups. On insecure systems, these restrictions may be relaxed, but this is not a portable assumption. On POSIX systems, you can detect this condition this way: use POSIX qw(sysconf _PC_CHOWN_RESTRICTED); $can_chown_giveaway = not sysconf(_PC_CHOWN_RESTRICTED); Portability issues: L<perlport/chmod>. =item chr NUMBER X<chr> X<character> X<ASCII> X<Unicode> =item chr =for Pod::Functions get character this number represents Returns the character represented by that NUMBER in the character set. For example, C<chr(65)> is C<"A"> in either ASCII or Unicode, and chr(0x263a) is a Unicode smiley face. Negative values give the Unicode replacement character (chr(0xfffd)), except under the L<bytes> pragma, where the low eight bits of the value (truncated to an integer) are used. If NUMBER is omitted, uses C<$_>. For the reverse, use L</ord>. Note that characters from 128 to 255 (inclusive) are by default internally not encoded as UTF-8 for backward compatibility reasons. See L<perlunicode> for more about Unicode. =item chroot FILENAME X<chroot> X<root> =item chroot =for Pod::Functions make directory new root for path lookups This function works like the system call by the same name: it makes the named directory the new root directory for all further pathnames that begin with a C</> by your process and all its children. (It doesn't change your current working directory, which is unaffected.) For security reasons, this call is restricted to the superuser. If FILENAME is omitted, does a C<chroot> to C<$_>. Portability issues: L<perlport/chroot>. =item close FILEHANDLE X<close> =item close =for Pod::Functions close file (or pipe or socket) handle Closes the file or pipe associated with the filehandle, flushes the IO buffers, and closes the system file descriptor. Returns true if those operations succeed and if no error was reported by any PerlIO layer. Closes the currently selected filehandle if the argument is omitted. You don't have to close FILEHANDLE if you are immediately going to do another C<open> on it, because C<open> closes it for you. (See L<open|/open FILEHANDLE>.) However, an explicit C<close> on an input file resets the line counter (C<$.>), while the implicit close done by C<open> does not. If the filehandle came from a piped open, C<close> returns false if one of the other syscalls involved fails or if its program exits with non-zero status. If the only problem was that the program exited non-zero, C<$!> will be set to C<0>. Closing a pipe also waits for the process executing on the pipe to exit--in case you wish to look at the output of the pipe afterwards--and implicitly puts the exit status value of that command into C<$?> and C<${^CHILD_ERROR_NATIVE}>. If there are multiple threads running, C<close> on a filehandle from a piped open returns true without waiting for the child process to terminate, if the filehandle is still open in another thread. Closing the read end of a pipe before the process writing to it at the other end is done writing results in the writer receiving a SIGPIPE. If the other end can't handle that, be sure to read all the data before closing the pipe. Example: open(OUTPUT, '|sort >foo') # pipe to sort or die "Can't start sort: $!"; #... # print stuff to output close OUTPUT # wait for sort to finish or warn $! ? "Error closing sort pipe: $!" : "Exit status $? from sort"; open(INPUT, 'foo') # get sort's results or die "Can't open 'foo' for input: $!"; FILEHANDLE may be an expression whose value can be used as an indirect filehandle, usually the real filehandle name or an autovivified handle. =item closedir DIRHANDLE X<closedir> =for Pod::Functions close directory handle Closes a directory opened by C<opendir> and returns the success of that system call. =item connect SOCKET,NAME X<connect> =for Pod::Functions connect to a remote socket Attempts to connect to a remote socket, just like connect(2). Returns true if it succeeded, false otherwise. NAME should be a packed address of the appropriate type for the socket. See the examples in L<perlipc/"Sockets: Client/Server Communication">. =item continue BLOCK X<continue> =item continue =for Pod::Functions optional trailing block in a while or foreach When followed by a BLOCK, C<continue> is actually a flow control statement rather than a function. If there is a C<continue> BLOCK attached to a BLOCK (typically in a C<while> or C<foreach>), it is always executed just before the conditional is about to be evaluated again, just like the third part of a C<for> loop in C. Thus it can be used to increment a loop variable, even when the loop has been continued via the C<next> statement (which is similar to the C C<continue> statement). C<last>, C<next>, or C<redo> may appear within a C<continue> block; C<last> and C<redo> behave as if they had been executed within the main block. So will C<next>, but since it will execute a C<continue> block, it may be more entertaining. while (EXPR) { ### redo always comes here do_something; } continue { ### next always comes here do_something_else; # then back the top to re-check EXPR } ### last always comes here Omitting the C<continue> section is equivalent to using an empty one, logically enough, so C<next> goes directly back to check the condition at the top of the loop. When there is no BLOCK, C<continue> is a function that falls through the current C<when> or C<default> block instead of iterating a dynamically enclosing C<foreach> or exiting a lexically enclosing C<given>. In Perl 5.14 and earlier, this form of C<continue> was only available when the C<"switch"> feature was enabled. See L<feature> and L<perlsyn/"Switch Statements"> for more information. =item cos EXPR X<cos> X<cosine> X<acos> X<arccosine> =item cos =for Pod::Functions cosine function Returns the cosine of EXPR (expressed in radians). If EXPR is omitted, takes the cosine of C<$_>. For the inverse cosine operation, you may use the C<Math::Trig::acos()> function, or use this relation: sub acos { atan2( sqrt(1 - $_[0] * $_[0]), $_[0] ) } =item crypt PLAINTEXT,SALT X<crypt> X<digest> X<hash> X<salt> X<plaintext> X<password> X<decrypt> X<cryptography> X<passwd> X<encrypt> =for Pod::Functions one-way passwd-style encryption Creates a digest string exactly like the crypt(3) function in the C library (assuming that you actually have a version there that has not been extirpated as a potential munition). crypt() is a one-way hash function. The PLAINTEXT and SALT are turned into a short string, called a digest, which is returned. The same PLAINTEXT and SALT will always return the same string, but there is no (known) way to get the original PLAINTEXT from the hash. Small changes in the PLAINTEXT or SALT will result in large changes in the digest. There is no decrypt function. This function isn't all that useful for cryptography (for that, look for F<Crypt> modules on your nearby CPAN mirror) and the name "crypt" is a bit of a misnomer. Instead it is primarily used to check if two pieces of text are the same without having to transmit or store the text itself. An example is checking if a correct password is given. The digest of the password is stored, not the password itself. The user types in a password that is crypt()'d with the same salt as the stored digest. If the two digests match, the password is correct. When verifying an existing digest string you should use the digest as the salt (like C<crypt($plain, $digest) eq $digest>). The SALT used to create the digest is visible as part of the digest. This ensures crypt() will hash the new string with the same salt as the digest. This allows your code to work with the standard L<crypt|/crypt> and with more exotic implementations. In other words, assume nothing about the returned string itself nor about how many bytes of SALT may matter. Traditionally the result is a string of 13 bytes: two first bytes of the salt, followed by 11 bytes from the set C<[./0-9A-Za-z]>, and only the first eight bytes of PLAINTEXT mattered. But alternative hashing schemes (like MD5), higher level security schemes (like C2), and implementations on non-Unix platforms may produce different strings. When choosing a new salt create a random two character string whose characters come from the set C<[./0-9A-Za-z]> (like C<join '', ('.', '/', 0..9, 'A'..'Z', 'a'..'z')[rand 64, rand 64]>). This set of characters is just a recommendation; the characters allowed in the salt depend solely on your system's crypt library, and Perl can't restrict what salts C<crypt()> accepts. Here's an example that makes sure that whoever runs this program knows their password: $pwd = (getpwuid($<))[1]; system "stty -echo"; print "Password: "; chomp($word = <STDIN>); print "\n"; system "stty echo"; if (crypt($word, $pwd) ne $pwd) { die "Sorry...\n"; } else { print "ok\n"; } Of course, typing in your own password to whoever asks you for it is unwise. The L<crypt|/crypt> function is unsuitable for hashing large quantities of data, not least of all because you can't get the information back. Look at the L<Digest> module for more robust algorithms. If using crypt() on a Unicode string (which I<potentially> has characters with codepoints above 255), Perl tries to make sense of the situation by trying to downgrade (a copy of) the string back to an eight-bit byte string before calling crypt() (on that copy). If that works, good. If not, crypt() dies with C<Wide character in crypt>. Portability issues: L<perlport/crypt>. =item dbmclose HASH X<dbmclose> =for Pod::Functions breaks binding on a tied dbm file [This function has been largely superseded by the C<untie> function.] Breaks the binding between a DBM file and a hash. Portability issues: L<perlport/dbmclose>. =item dbmopen HASH,DBNAME,MASK X<dbmopen> X<dbm> X<ndbm> X<sdbm> X<gdbm> =for Pod::Functions create binding on a tied dbm file [This function has been largely superseded by the L<tie|/tie VARIABLE,CLASSNAME,LIST> function.] This binds a dbm(3), ndbm(3), sdbm(3), gdbm(3), or Berkeley DB file to a hash. HASH is the name of the hash. (Unlike normal C<open>, the first argument is I<not> a filehandle, even though it looks like one). DBNAME is the name of the database (without the F<.dir> or F<.pag> extension if any). If the database does not exist, it is created with protection specified by MASK (as modified by the C<umask>). To prevent creation of the database if it doesn't exist, you may specify a MODE of 0, and the function will return a false value if it can't find an existing database. If your system supports only the older DBM functions, you may make only one C<dbmopen> call in your program. In older versions of Perl, if your system had neither DBM nor ndbm, calling C<dbmopen> produced a fatal error; it now falls back to sdbm(3). If you don't have write access to the DBM file, you can only read hash variables, not set them. If you want to test whether you can write, either use file tests or try setting a dummy hash entry inside an C<eval> to trap the error. Note that functions such as C<keys> and C<values> may return huge lists when used on large DBM files. You may prefer to use the C<each> function to iterate over large DBM files. Example: # print out history file offsets dbmopen(%HIST,'/usr/lib/news/history',0666); while (($key,$val) = each %HIST) { print $key, ' = ', unpack('L',$val), "\n"; } dbmclose(%HIST); See also L<AnyDBM_File> for a more general description of the pros and cons of the various dbm approaches, as well as L<DB_File> for a particularly rich implementation. You can control which DBM library you use by loading that library before you call dbmopen(): use DB_File; dbmopen(%NS_Hist, "$ENV{HOME}/.netscape/history.db") or die "Can't open netscape history file: $!"; Portability issues: L<perlport/dbmopen>. =item defined EXPR X<defined> X<undef> X<undefined> =item defined =for Pod::Functions test whether a value, variable, or function is defined Returns a Boolean value telling whether EXPR has a value other than the undefined value C<undef>. If EXPR is not present, C<$_> is checked. Many operations return C<undef> to indicate failure, end of file, system error, uninitialized variable, and other exceptional conditions. This function allows you to distinguish C<undef> from other values. (A simple Boolean test will not distinguish among C<undef>, zero, the empty string, and C<"0">, which are all equally false.) Note that since C<undef> is a valid scalar, its presence doesn't I<necessarily> indicate an exceptional condition: C<pop> returns C<undef> when its argument is an empty array, I<or> when the element to return happens to be C<undef>. You may also use C<defined(&func)> to check whether subroutine C<&func> has ever been defined. The return value is unaffected by any forward declarations of C<&func>. A subroutine that is not defined may still be callable: its package may have an C<AUTOLOAD> method that makes it spring into existence the first time that it is called; see L<perlsub>. Use of C<defined> on aggregates (hashes and arrays) is deprecated. It used to report whether memory for that aggregate had ever been allocated. This behavior may disappear in future versions of Perl. You should instead use a simple test for size: if (@an_array) { print "has array elements\n" } if (%a_hash) { print "has hash members\n" } When used on a hash element, it tells you whether the value is defined, not whether the key exists in the hash. Use L</exists> for the latter purpose. Examples: print if defined $switch{D}; print "$val\n" while defined($val = pop(@ary)); die "Can't readlink $sym: $!" unless defined($value = readlink $sym); sub foo { defined &$bar ? &$bar(@_) : die "No bar"; } $debugging = 0 unless defined $debugging; Note: Many folks tend to overuse C<defined> and are then surprised to discover that the number C<0> and C<""> (the zero-length string) are, in fact, defined values. For example, if you say "ab" =~ /a(.*)b/; The pattern match succeeds and C<$1> is defined, although it matched "nothing". It didn't really fail to match anything. Rather, it matched something that happened to be zero characters long. This is all very above-board and honest. When a function returns an undefined value, it's an admission that it couldn't give you an honest answer. So you should use C<defined> only when questioning the integrity of what you're trying to do. At other times, a simple comparison to C<0> or C<""> is what you want. See also L</undef>, L</exists>, L</ref>. =item delete EXPR X<delete> =for Pod::Functions deletes a value from a hash Given an expression that specifies an element or slice of a hash, C<delete> deletes the specified elements from that hash so that exists() on that element no longer returns true. Setting a hash element to the undefined value does not remove its key, but deleting it does; see L</exists>. In list context, returns the value or values deleted, or the last such element in scalar context. The return list's length always matches that of the argument list: deleting non-existent elements returns the undefined value in their corresponding positions. delete() may also be used on arrays and array slices, but its behavior is less straightforward. Although exists() will return false for deleted entries, deleting array elements never changes indices of existing values; use shift() or splice() for that. However, if all deleted elements fall at the end of an array, the array's size shrinks to the position of the highest element that still tests true for exists(), or to 0 if none do. B<WARNING:> Calling delete on array values is deprecated and likely to be removed in a future version of Perl. Deleting from C<%ENV> modifies the environment. Deleting from a hash tied to a DBM file deletes the entry from the DBM file. Deleting from a C<tied> hash or array may not necessarily return anything; it depends on the implementation of the C<tied> package's DELETE method, which may do whatever it pleases. The C<delete local EXPR> construct localizes the deletion to the current block at run time. Until the block exits, elements locally deleted temporarily no longer exist. See L<perlsub/"Localized deletion of elements of composite types">. %hash = (foo => 11, bar => 22, baz => 33); $scalar = delete $hash{foo}; # $scalar is 11 $scalar = delete @hash{qw(foo bar)}; # $scalar is 22 @array = delete @hash{qw(foo bar baz)}; # @array is (undef,undef,33) The following (inefficiently) deletes all the values of %HASH and @ARRAY: foreach $key (keys %HASH) { delete $HASH{$key}; } foreach $index (0 .. $#ARRAY) { delete $ARRAY[$index]; } And so do these: delete @HASH{keys %HASH}; delete @ARRAY[0 .. $#ARRAY]; But both are slower than assigning the empty list or undefining %HASH or @ARRAY, which is the customary way to empty out an aggregate: %HASH = (); # completely empty %HASH undef %HASH; # forget %HASH ever existed @ARRAY = (); # completely empty @ARRAY undef @ARRAY; # forget @ARRAY ever existed The EXPR can be arbitrarily complicated provided its final operation is an element or slice of an aggregate: delete $ref->[$x][$y]{$key}; delete @{$ref->[$x][$y]}{$key1, $key2, @morekeys}; delete $ref->[$x][$y][$index]; delete @{$ref->[$x][$y]}[$index1, $index2, @moreindices]; =item die LIST X<die> X<throw> X<exception> X<raise> X<$@> X<abort> =for Pod::Functions raise an exception or bail out C<die> raises an exception. Inside an C<eval> the error message is stuffed into C<$@> and the C<eval> is terminated with the undefined value. If the exception is outside of all enclosing C<eval>s, then the uncaught exception prints LIST to C<STDERR> and exits with a non-zero value. If you need to exit the process with a specific exit code, see L</exit>. Equivalent examples: die "Can't cd to spool: $!\n" unless chdir '/usr/spool/news'; chdir '/usr/spool/news' or die "Can't cd to spool: $!\n" If the last element of LIST does not end in a newline, the current script line number and input line number (if any) are also printed, and a newline is supplied. Note that the "input line number" (also known as "chunk") is subject to whatever notion of "line" happens to be currently in effect, and is also available as the special variable C<$.>. See L<perlvar/"$/"> and L<perlvar/"$.">. Hint: sometimes appending C<", stopped"> to your message will cause it to make better sense when the string C<"at foo line 123"> is appended. Suppose you are running script "canasta". die "/etc/games is no good"; die "/etc/games is no good, stopped"; produce, respectively /etc/games is no good at canasta line 123. /etc/games is no good, stopped at canasta line 123. If the output is empty and C<$@> already contains a value (typically from a previous eval) that value is reused after appending C<"\t...propagated">. This is useful for propagating exceptions: eval { ... }; die unless $@ =~ /Expected exception/; If the output is empty and C<$@> contains an object reference that has a C<PROPAGATE> method, that method will be called with additional file and line number parameters. The return value replaces the value in C<$@>; i.e., as if C<< $@ = eval { $@->PROPAGATE(__FILE__, __LINE__) }; >> were called. If C<$@> is empty then the string C<"Died"> is used. If an uncaught exception results in interpreter exit, the exit code is determined from the values of C<$!> and C<$?> with this pseudocode: exit $! if $!; # errno exit $? >> 8 if $? >> 8; # child exit status exit 255; # last resort The intent is to squeeze as much possible information about the likely cause into the limited space of the system exit code. However, as C<$!> is the value of C's C<errno>, which can be set by any system call, this means that the value of the exit code used by C<die> can be non-predictable, so should not be relied upon, other than to be non-zero. You can also call C<die> with a reference argument, and if this is trapped within an C<eval>, C<$@> contains that reference. This permits more elaborate exception handling using objects that maintain arbitrary state about the exception. Such a scheme is sometimes preferable to matching particular string values of C<$@> with regular expressions. Because C<$@> is a global variable and C<eval> may be used within object implementations, be careful that analyzing the error object doesn't replace the reference in the global variable. It's easiest to make a local copy of the reference before any manipulations. Here's an example: use Scalar::Util "blessed"; eval { ... ; die Some::Module::Exception->new( FOO => "bar" ) }; if (my $ev_err = $@) { if (blessed($ev_err) && $ev_err->isa("Some::Module::Exception")) { # handle Some::Module::Exception } else { # handle all other possible exceptions } } Because Perl stringifies uncaught exception messages before display, you'll probably want to overload stringification operations on exception objects. See L<overload> for details about that. You can arrange for a callback to be run just before the C<die> does its deed, by setting the C<$SIG{__DIE__}> hook. The associated handler is called with the error text and can change the error message, if it sees fit, by calling C<die> again. See L<perlvar/%SIG> for details on setting C<%SIG> entries, and L<"eval BLOCK"> for some examples. Although this feature was to be run only right before your program was to exit, this is not currently so: the C<$SIG{__DIE__}> hook is currently called even inside eval()ed blocks/strings! If one wants the hook to do nothing in such situations, put die @_ if $^S; as the first line of the handler (see L<perlvar/$^S>). Because this promotes strange action at a distance, this counterintuitive behavior may be fixed in a future release. See also exit(), warn(), and the Carp module. =item do BLOCK X<do> X<block> =for Pod::Functions turn a BLOCK into a TERM Not really a function. Returns the value of the last command in the sequence of commands indicated by BLOCK. When modified by the C<while> or C<until> loop modifier, executes the BLOCK once before testing the loop condition. (On other statements the loop modifiers test the conditional first.) C<do BLOCK> does I<not> count as a loop, so the loop control statements C<next>, C<last>, or C<redo> cannot be used to leave or restart the block. See L<perlsyn> for alternative strategies. =item do SUBROUTINE(LIST) X<do> This form of subroutine call is deprecated. SUBROUTINE can be a bareword, a scalar variable or a subroutine beginning with C<&>. =item do EXPR X<do> Uses the value of EXPR as a filename and executes the contents of the file as a Perl script. do 'stat.pl'; is just like eval `cat stat.pl`; except that it's more efficient and concise, keeps track of the current filename for error messages, searches the C<@INC> directories, and updates C<%INC> if the file is found. See L<perlvar/@INC> and L<perlvar/%INC> for these variables. It also differs in that code evaluated with C<do FILENAME> cannot see lexicals in the enclosing scope; C<eval STRING> does. It's the same, however, in that it does reparse the file every time you call it, so you probably don't want to do this inside a loop. If C<do> can read the file but cannot compile it, it returns C<undef> and sets an error message in C<$@>. If C<do> cannot read the file, it returns undef and sets C<$!> to the error. Always check C<$@> first, as compilation could fail in a way that also sets C<$!>. If the file is successfully compiled, C<do> returns the value of the last expression evaluated. Inclusion of library modules is better done with the C<use> and C<require> operators, which also do automatic error checking and raise an exception if there's a problem. You might like to use C<do> to read in a program configuration file. Manual error checking can be done this way: # read in config files: system first, then user for $file ("/share/prog/defaults.rc", "$ENV{HOME}/.someprogrc") { unless ($return = do $file) { warn "couldn't parse $file: $@" if $@; warn "couldn't do $file: $!" unless defined $return; warn "couldn't run $file" unless $return; } } =item dump LABEL X<dump> X<core> X<undump> =item dump =for Pod::Functions create an immediate core dump This function causes an immediate core dump. See also the B<-u> command-line switch in L<perlrun>, which does the same thing. Primarily this is so that you can use the B<undump> program (not supplied) to turn your core dump into an executable binary after having initialized all your variables at the beginning of the program. When the new binary is executed it will begin by executing a C<goto LABEL> (with all the restrictions that C<goto> suffers). Think of it as a goto with an intervening core dump and reincarnation. If C<LABEL> is omitted, restarts the program from the top. B<WARNING>: Any files opened at the time of the dump will I<not> be open any more when the program is reincarnated, with possible resulting confusion by Perl. This function is now largely obsolete, mostly because it's very hard to convert a core file into an executable. That's why you should now invoke it as C<CORE::dump()>, if you don't want to be warned against a possible typo. Portability issues: L<perlport/dump>. =item each HASH X<each> X<hash, iterator> =item each ARRAY X<array, iterator> =item each EXPR =for Pod::Functions retrieve the next key/value pair from a hash When called on a hash in list context, returns a 2-element list consisting of the key and value for the next element of a hash. In Perl 5.12 and later only, it will also return the index and value for the next element of an array so that you can iterate over it; older Perls consider this a syntax error. When called in scalar context, returns only the key (not the value) in a hash, or the index in an array. Hash entries are returned in an apparently random order. The actual random order is subject to change in future versions of Perl, but it is guaranteed to be in the same order as either the C<keys> or C<values> function would produce on the same (unmodified) hash. Since Perl 5.8.2 the ordering can be different even between different runs of Perl for security reasons (see L<perlsec/"Algorithmic Complexity Attacks">). After C<each> has returned all entries from the hash or array, the next call to C<each> returns the empty list in list context and C<undef> in scalar context; the next call following I<that> one restarts iteration. Each hash or array has its own internal iterator, accessed by C<each>, C<keys>, and C<values>. The iterator is implicitly reset when C<each> has reached the end as just described; it can be explicitly reset by calling C<keys> or C<values> on the hash or array. If you add or delete a hash's elements while iterating over it, entries may be skipped or duplicated--so don't do that. Exception: In the current implementation, it is always safe to delete the item most recently returned by C<each()>, so the following code works properly: while (($key, $value) = each %hash) { print $key, "\n"; delete $hash{$key}; # This is safe } This prints out your environment like the printenv(1) program, but in a different order: while (($key,$value) = each %ENV) { print "$key=$value\n"; } Starting with Perl 5.14, C<each> can take a scalar EXPR, which must hold reference to an unblessed hash or array. The argument will be dereferenced automatically. This aspect of C<each> is considered highly experimental. The exact behaviour may change in a future version of Perl. while (($key,$value) = each $hashref) { ... } To avoid confusing would-be users of your code who are running earlier versions of Perl with mysterious syntax errors, put this sort of thing at the top of your file to signal that your code will work I<only> on Perls of a recent vintage: use 5.012; # so keys/values/each work on arrays use 5.014; # so keys/values/each work on scalars (experimental) See also C<keys>, C<values>, and C<sort>. =item eof FILEHANDLE X<eof> X<end of file> X<end-of-file> =item eof () =item eof =for Pod::Functions test a filehandle for its end Returns 1 if the next read on FILEHANDLE will return end of file I<or> if FILEHANDLE is not open. FILEHANDLE may be an expression whose value gives the real filehandle. (Note that this function actually reads a character and then C<ungetc>s it, so isn't useful in an interactive context.) Do not read from a terminal file (or call C<eof(FILEHANDLE)> on it) after end-of-file is reached. File types such as terminals may lose the end-of-file condition if you do. An C<eof> without an argument uses the last file read. Using C<eof()> with empty parentheses is different. It refers to the pseudo file formed from the files listed on the command line and accessed via the C<< <> >> operator. Since C<< <> >> isn't explicitly opened, as a normal filehandle is, an C<eof()> before C<< <> >> has been used will cause C<@ARGV> to be examined to determine if input is available. Similarly, an C<eof()> after C<< <> >> has returned end-of-file will assume you are processing another C<@ARGV> list, and if you haven't set C<@ARGV>, will read input from C<STDIN>; see L<perlop/"I/O Operators">. In a C<< while (<>) >> loop, C<eof> or C<eof(ARGV)> can be used to detect the end of each file, whereas C<eof()> will detect the end of the very last file only. Examples: # reset line numbering on each input file while (<>) { next if /^\s*#/; # skip comments print "$.\t$_"; } continue { close ARGV if eof; # Not eof()! } # insert dashes just before last line of last file while (<>) { if (eof()) { # check for end of last file print "--------------\n"; } print; last if eof(); # needed if we're reading from a terminal } Practical hint: you almost never need to use C<eof> in Perl, because the input operators typically return C<undef> when they run out of data or encounter an error. =item eval EXPR X<eval> X<try> X<catch> X<evaluate> X<parse> X<execute> X<error, handling> X<exception, handling> =item eval BLOCK =item eval =for Pod::Functions catch exceptions or compile and run code In the first form, the return value of EXPR is parsed and executed as if it were a little Perl program. The value of the expression (which is itself determined within scalar context) is first parsed, and if there were no errors, executed as a block within the lexical context of the current Perl program. This means, that in particular, any outer lexical variables are visible to it, and any package variable settings or subroutine and format definitions remain afterwards. Note that the value is parsed every time the C<eval> executes. If EXPR is omitted, evaluates C<$_>. This form is typically used to delay parsing and subsequent execution of the text of EXPR until run time. If the C<unicode_eval> feature is enabled (which is the default under a C<use 5.16> or higher declaration), EXPR or C<$_> is treated as a string of characters, so C<use utf8> declarations have no effect, and source filters are forbidden. In the absence of the C<unicode_eval> feature, the string will sometimes be treated as characters and sometimes as bytes, depending on the internal encoding, and source filters activated within the C<eval> exhibit the erratic, but historical, behaviour of affecting some outer file scope that is still compiling. See also the L</evalbytes> keyword, which always treats its input as a byte stream and works properly with source filters, and the L<feature> pragma. In the second form, the code within the BLOCK is parsed only once--at the same time the code surrounding the C<eval> itself was parsed--and executed within the context of the current Perl program. This form is typically used to trap exceptions more efficiently than the first (see below), while also providing the benefit of checking the code within BLOCK at compile time. The final semicolon, if any, may be omitted from the value of EXPR or within the BLOCK. In both forms, the value returned is the value of the last expression evaluated inside the mini-program; a return statement may be also used, just as with subroutines. The expression providing the return value is evaluated in void, scalar, or list context, depending on the context of the C<eval> itself. See L</wantarray> for more on how the evaluation context can be determined. If there is a syntax error or runtime error, or a C<die> statement is executed, C<eval> returns C<undef> in scalar context or an empty list in list context, and C<$@> is set to the error message. (Prior to 5.16, a bug caused C<undef> to be returned in list context for syntax errors, but not for runtime errors.) If there was no error, C<$@> is set to the empty string. A control flow operator like C<last> or C<goto> can bypass the setting of C<$@>. Beware that using C<eval> neither silences Perl from printing warnings to STDERR, nor does it stuff the text of warning messages into C<$@>. To do either of those, you have to use the C<$SIG{__WARN__}> facility, or turn off warnings inside the BLOCK or EXPR using S<C<no warnings 'all'>>. See L</warn>, L<perlvar>, L<warnings> and L<perllexwarn>. Note that, because C<eval> traps otherwise-fatal errors, it is useful for determining whether a particular feature (such as C<socket> or C<symlink>) is implemented. It is also Perl's exception-trapping mechanism, where the die operator is used to raise exceptions. If you want to trap errors when loading an XS module, some problems with the binary interface (such as Perl version skew) may be fatal even with C<eval> unless C<$ENV{PERL_DL_NONLAZY}> is set. See L<perlrun>. If the code to be executed doesn't vary, you may use the eval-BLOCK form to trap run-time errors without incurring the penalty of recompiling each time. The error, if any, is still returned in C<$@>. Examples: # make divide-by-zero nonfatal eval { $answer = $a / $b; }; warn $@ if $@; # same thing, but less efficient eval '$answer = $a / $b'; warn $@ if $@; # a compile-time error eval { $answer = }; # WRONG # a run-time error eval '$answer ='; # sets $@ Using the C<eval{}> form as an exception trap in libraries does have some issues. Due to the current arguably broken state of C<__DIE__> hooks, you may wish not to trigger any C<__DIE__> hooks that user code may have installed. You can use the C<local $SIG{__DIE__}> construct for this purpose, as this example shows: # a private exception trap for divide-by-zero eval { local $SIG{'__DIE__'}; $answer = $a / $b; }; warn $@ if $@; This is especially significant, given that C<__DIE__> hooks can call C<die> again, which has the effect of changing their error messages: # __DIE__ hooks may modify error messages { local $SIG{'__DIE__'} = sub { (my $x = $_[0]) =~ s/foo/bar/g; die $x }; eval { die "foo lives here" }; print $@ if $@; # prints "bar lives here" } Because this promotes action at a distance, this counterintuitive behavior may be fixed in a future release. With an C<eval>, you should be especially careful to remember what's being looked at when: eval $x; # CASE 1 eval "$x"; # CASE 2 eval '$x'; # CASE 3 eval { $x }; # CASE 4 eval "\$$x++"; # CASE 5 $$x++; # CASE 6 Cases 1 and 2 above behave identically: they run the code contained in the variable $x. (Although case 2 has misleading double quotes making the reader wonder what else might be happening (nothing is).) Cases 3 and 4 likewise behave in the same way: they run the code C<'$x'>, which does nothing but return the value of $x. (Case 4 is preferred for purely visual reasons, but it also has the advantage of compiling at compile-time instead of at run-time.) Case 5 is a place where normally you I<would> like to use double quotes, except that in this particular situation, you can just use symbolic references instead, as in case 6. Before Perl 5.14, the assignment to C<$@> occurred before restoration of localized variables, which means that for your code to run on older versions, a temporary is required if you want to mask some but not all errors: # alter $@ on nefarious repugnancy only { my $e; { local $@; # protect existing $@ eval { test_repugnancy() }; # $@ =~ /nefarious/ and die $@; # Perl 5.14 and higher only $@ =~ /nefarious/ and $e = $@; } die $e if defined $e } C<eval BLOCK> does I<not> count as a loop, so the loop control statements C<next>, C<last>, or C<redo> cannot be used to leave or restart the block. An C<eval ''> executed within the C<DB> package doesn't see the usual surrounding lexical scope, but rather the scope of the first non-DB piece of code that called it. You don't normally need to worry about this unless you are writing a Perl debugger. =item evalbytes EXPR X<evalbytes> =item evalbytes =for Pod::Functions +evalbytes similar to string eval, but intend to parse a bytestream This function is like L</eval> with a string argument, except it always parses its argument, or C<$_> if EXPR is omitted, as a string of bytes. A string containing characters whose ordinal value exceeds 255 results in an error. Source filters activated within the evaluated code apply to the code itself. This function is only available under the C<evalbytes> feature, a C<use v5.16> (or higher) declaration, or with a C<CORE::> prefix. See L<feature> for more information. =item exec LIST X<exec> X<execute> =item exec PROGRAM LIST =for Pod::Functions abandon this program to run another The C<exec> function executes a system command I<and never returns>; use C<system> instead of C<exec> if you want it to return. It fails and returns false only if the command does not exist I<and> it is executed directly instead of via your system's command shell (see below). Since it's a common mistake to use C<exec> instead of C<system>, Perl warns you if C<exec> is called in void context and if there is a following statement that isn't C<die>, C<warn>, or C<exit> (if C<-w> is set--but you always do that, right?). If you I<really> want to follow an C<exec> with some other statement, you can use one of these styles to avoid the warning: exec ('foo') or print STDERR "couldn't exec foo: $!"; { exec ('foo') }; print STDERR "couldn't exec foo: $!"; If there is more than one argument in LIST, or if LIST is an array with more than one value, calls execvp(3) with the arguments in LIST. If there is only one scalar argument or an array with one element in it, the argument is checked for shell metacharacters, and if there are any, the entire argument is passed to the system's command shell for parsing (this is C</bin/sh -c> on Unix platforms, but varies on other platforms). If there are no shell metacharacters in the argument, it is split into words and passed directly to C<execvp>, which is more efficient. Examples: exec '/bin/echo', 'Your arguments are: ', @ARGV; exec "sort $outfile | uniq"; If you don't really want to execute the first argument, but want to lie to the program you are executing about its own name, you can specify the program you actually want to run as an "indirect object" (without a comma) in front of the LIST. (This always forces interpretation of the LIST as a multivalued list, even if there is only a single scalar in the list.) Example: $shell = '/bin/csh'; exec $shell '-sh'; # pretend it's a login shell or, more directly, exec {'/bin/csh'} '-sh'; # pretend it's a login shell When the arguments get executed via the system shell, results are subject to its quirks and capabilities. See L<perlop/"`STRING`"> for details. Using an indirect object with C<exec> or C<system> is also more secure. This usage (which also works fine with system()) forces interpretation of the arguments as a multivalued list, even if the list had just one argument. That way you're safe from the shell expanding wildcards or splitting up words with whitespace in them. @args = ( "echo surprise" ); exec @args; # subject to shell escapes # if @args == 1 exec { $args[0] } @args; # safe even with one-arg list The first version, the one without the indirect object, ran the I<echo> program, passing it C<"surprise"> an argument. The second version didn't; it tried to run a program named I<"echo surprise">, didn't find it, and set C<$?> to a non-zero value indicating failure. Beginning with v5.6.0, Perl attempts to flush all files opened for output before the exec, but this may not be supported on some platforms (see L<perlport>). To be safe, you may need to set C<$|> ($AUTOFLUSH in English) or call the C<autoflush()> method of C<IO::Handle> on any open handles to avoid lost output. Note that C<exec> will not call your C<END> blocks, nor will it invoke C<DESTROY> methods on your objects. Portability issues: L<perlport/exec>. =item exists EXPR X<exists> X<autovivification> =for Pod::Functions test whether a hash key is present Given an expression that specifies an element of a hash, returns true if the specified element in the hash has ever been initialized, even if the corresponding value is undefined. print "Exists\n" if exists $hash{$key}; print "Defined\n" if defined $hash{$key}; print "True\n" if $hash{$key}; exists may also be called on array elements, but its behavior is much less obvious and is strongly tied to the use of L</delete> on arrays. B<Be aware> that calling exists on array values is deprecated and likely to be removed in a future version of Perl. print "Exists\n" if exists $array[$index]; print "Defined\n" if defined $array[$index]; print "True\n" if $array[$index]; A hash or array element can be true only if it's defined and defined only if it exists, but the reverse doesn't necessarily hold true. Given an expression that specifies the name of a subroutine, returns true if the specified subroutine has ever been declared, even if it is undefined. Mentioning a subroutine name for exists or defined does not count as declaring it. Note that a subroutine that does not exist may still be callable: its package may have an C<AUTOLOAD> method that makes it spring into existence the first time that it is called; see L<perlsub>. print "Exists\n" if exists &subroutine; print "Defined\n" if defined &subroutine; Note that the EXPR can be arbitrarily complicated as long as the final operation is a hash or array key lookup or subroutine name: if (exists $ref->{A}->{B}->{$key}) { } if (exists $hash{A}{B}{$key}) { } if (exists $ref->{A}->{B}->[$ix]) { } if (exists $hash{A}{B}[$ix]) { } if (exists &{$ref->{A}{B}{$key}}) { } Although the most deeply nested array or hash element will not spring into existence just because its existence was tested, any intervening ones will. Thus C<< $ref->{"A"} >> and C<< $ref->{"A"}->{"B"} >> will spring into existence due to the existence test for the $key element above. This happens anywhere the arrow operator is used, including even here: undef $ref; if (exists $ref->{"Some key"}) { } print $ref; # prints HASH(0x80d3d5c) This surprising autovivification in what does not at first--or even second--glance appear to be an lvalue context may be fixed in a future release. Use of a subroutine call, rather than a subroutine name, as an argument to exists() is an error. exists &sub; # OK exists &sub(); # Error =item exit EXPR X<exit> X<terminate> X<abort> =item exit =for Pod::Functions terminate this program Evaluates EXPR and exits immediately with that value. Example: $ans = <STDIN>; exit 0 if $ans =~ /^[Xx]/; See also C<die>. If EXPR is omitted, exits with C<0> status. The only universally recognized values for EXPR are C<0> for success and C<1> for error; other values are subject to interpretation depending on the environment in which the Perl program is running. For example, exiting 69 (EX_UNAVAILABLE) from a I<sendmail> incoming-mail filter will cause the mailer to return the item undelivered, but that's not true everywhere. Don't use C<exit> to abort a subroutine if there's any chance that someone might want to trap whatever error happened. Use C<die> instead, which can be trapped by an C<eval>. The exit() function does not always exit immediately. It calls any defined C<END> routines first, but these C<END> routines may not themselves abort the exit. Likewise any object destructors that need to be called are called before the real exit. C<END> routines and destructors can change the exit status by modifying C<$?>. If this is a problem, you can call C<POSIX::_exit($status)> to avoid END and destructor processing. See L<perlmod> for details. Portability issues: L<perlport/exit>. =item exp EXPR X<exp> X<exponential> X<antilog> X<antilogarithm> X<e> =item exp =for Pod::Functions raise I<e> to a power Returns I<e> (the natural logarithm base) to the power of EXPR. If EXPR is omitted, gives C<exp($_)>. =item fc EXPR X<fc> X<foldcase> X<casefold> X<fold-case> X<case-fold> =item fc =for Pod::Functions +fc return casefolded version of a string Returns the casefolded version of EXPR. This is the internal function implementing the C<\F> escape in double-quoted strings. Casefolding is the process of mapping strings to a form where case differences are erased; comparing two strings in their casefolded form is effectively a way of asking if two strings are equal, regardless of case. Roughly, if you ever found yourself writing this lc($this) eq lc($that) # Wrong! # or uc($this) eq uc($that) # Also wrong! # or $this =~ /\Q$that/i # Right! Now you can write fc($this) eq fc($that) And get the correct results. Perl only implements the full form of casefolding. For further information on casefolding, refer to the Unicode Standard, specifically sections 3.13 C<Default Case Operations>, 4.2 C<Case-Normative>, and 5.18 C<Case Mappings>, available at L<http://www.unicode.org/versions/latest/>, as well as the Case Charts available at L<http://www.unicode.org/charts/case/>. If EXPR is omitted, uses C<$_>. This function behaves the same way under various pragma, such as in a locale, as L</lc> does. While the Unicode Standard defines two additional forms of casefolding, one for Turkic languages and one that never maps one character into multiple characters, these are not provided by the Perl core; However, the CPAN module C<Unicode::Casing> may be used to provide an implementation. This keyword is available only when the C<"fc"> feature is enabled, or when prefixed with C<CORE::>; See L<feature>. Alternately, include a C<use v5.16> or later to the current scope. =item fcntl FILEHANDLE,FUNCTION,SCALAR X<fcntl> =for Pod::Functions file control system call Implements the fcntl(2) function. You'll probably have to say use Fcntl; first to get the correct constant definitions. Argument processing and value returned work just like C<ioctl> below. For example: use Fcntl; fcntl($filehandle, F_GETFL, $packed_return_buffer) or die "can't fcntl F_GETFL: $!"; You don't have to check for C<defined> on the return from C<fcntl>. Like C<ioctl>, it maps a C<0> return from the system call into C<"0 but true"> in Perl. This string is true in boolean context and C<0> in numeric context. It is also exempt from the normal B<-w> warnings on improper numeric conversions. Note that C<fcntl> raises an exception if used on a machine that doesn't implement fcntl(2). See the Fcntl module or your fcntl(2) manpage to learn what functions are available on your system. Here's an example of setting a filehandle named C<REMOTE> to be non-blocking at the system level. You'll have to negotiate C<$|> on your own, though. use Fcntl qw(F_GETFL F_SETFL O_NONBLOCK); $flags = fcntl(REMOTE, F_GETFL, 0) or die "Can't get flags for the socket: $!\n"; $flags = fcntl(REMOTE, F_SETFL, $flags | O_NONBLOCK) or die "Can't set flags for the socket: $!\n"; Portability issues: L<perlport/fcntl>. =item __FILE__ X<__FILE__> =for Pod::Functions the name of the current source file A special token that returns the name of the file in which it occurs. =item fileno FILEHANDLE X<fileno> =for Pod::Functions return file descriptor from filehandle Returns the file descriptor for a filehandle, or undefined if the filehandle is not open. If there is no real file descriptor at the OS level, as can happen with filehandles connected to memory objects via C<open> with a reference for the third argument, -1 is returned. This is mainly useful for constructing bitmaps for C<select> and low-level POSIX tty-handling operations. If FILEHANDLE is an expression, the value is taken as an indirect filehandle, generally its name. You can use this to find out whether two handles refer to the same underlying descriptor: if (fileno(THIS) == fileno(THAT)) { print "THIS and THAT are dups\n"; } =item flock FILEHANDLE,OPERATION X<flock> X<lock> X<locking> =for Pod::Functions lock an entire file with an advisory lock Calls flock(2), or an emulation of it, on FILEHANDLE. Returns true for success, false on failure. Produces a fatal error if used on a machine that doesn't implement flock(2), fcntl(2) locking, or lockf(3). C<flock> is Perl's portable file-locking interface, although it locks entire files only, not records. Two potentially non-obvious but traditional C<flock> semantics are that it waits indefinitely until the lock is granted, and that its locks are B<merely advisory>. Such discretionary locks are more flexible, but offer fewer guarantees. This means that programs that do not also use C<flock> may modify files locked with C<flock>. See L<perlport>, your port's specific documentation, and your system-specific local manpages for details. It's best to assume traditional behavior if you're writing portable programs. (But if you're not, you should as always feel perfectly free to write for your own system's idiosyncrasies (sometimes called "features"). Slavish adherence to portability concerns shouldn't get in the way of your getting your job done.) OPERATION is one of LOCK_SH, LOCK_EX, or LOCK_UN, possibly combined with LOCK_NB. These constants are traditionally valued 1, 2, 8 and 4, but you can use the symbolic names if you import them from the L<Fcntl> module, either individually, or as a group using the C<:flock> tag. LOCK_SH requests a shared lock, LOCK_EX requests an exclusive lock, and LOCK_UN releases a previously requested lock. If LOCK_NB is bitwise-or'ed with LOCK_SH or LOCK_EX, then C<flock> returns immediately rather than blocking waiting for the lock; check the return status to see if you got it. To avoid the possibility of miscoordination, Perl now flushes FILEHANDLE before locking or unlocking it. Note that the emulation built with lockf(3) doesn't provide shared locks, and it requires that FILEHANDLE be open with write intent. These are the semantics that lockf(3) implements. Most if not all systems implement lockf(3) in terms of fcntl(2) locking, though, so the differing semantics shouldn't bite too many people. Note that the fcntl(2) emulation of flock(3) requires that FILEHANDLE be open with read intent to use LOCK_SH and requires that it be open with write intent to use LOCK_EX. Note also that some versions of C<flock> cannot lock things over the network; you would need to use the more system-specific C<fcntl> for that. If you like you can force Perl to ignore your system's flock(2) function, and so provide its own fcntl(2)-based emulation, by passing the switch C<-Ud_flock> to the F<Configure> program when you configure and build a new Perl. Here's a mailbox appender for BSD systems. use Fcntl qw(:flock SEEK_END); # import LOCK_* and SEEK_END constants sub lock { my ($fh) = @_; flock($fh, LOCK_EX) or die "Cannot lock mailbox - $!\n"; # and, in case someone appended while we were waiting... seek($fh, 0, SEEK_END) or die "Cannot seek - $!\n"; } sub unlock { my ($fh) = @_; flock($fh, LOCK_UN) or die "Cannot unlock mailbox - $!\n"; } open(my $mbox, ">>", "/usr/spool/mail/$ENV{'USER'}") or die "Can't open mailbox: $!"; lock($mbox); print $mbox $msg,"\n\n"; unlock($mbox); On systems that support a real flock(2), locks are inherited across fork() calls, whereas those that must resort to the more capricious fcntl(2) function lose their locks, making it seriously harder to write servers. See also L<DB_File> for other flock() examples. Portability issues: L<perlport/flock>. =item fork X<fork> X<child> X<parent> =for Pod::Functions create a new process just like this one Does a fork(2) system call to create a new process running the same program at the same point. It returns the child pid to the parent process, C<0> to the child process, or C<undef> if the fork is unsuccessful. File descriptors (and sometimes locks on those descriptors) are shared, while everything else is copied. On most systems supporting fork(), great care has gone into making it extremely efficient (for example, using copy-on-write technology on data pages), making it the dominant paradigm for multitasking over the last few decades. Beginning with v5.6.0, Perl attempts to flush all files opened for output before forking the child process, but this may not be supported on some platforms (see L<perlport>). To be safe, you may need to set C<$|> ($AUTOFLUSH in English) or call the C<autoflush()> method of C<IO::Handle> on any open handles to avoid duplicate output. If you C<fork> without ever waiting on your children, you will accumulate zombies. On some systems, you can avoid this by setting C<$SIG{CHLD}> to C<"IGNORE">. See also L<perlipc> for more examples of forking and reaping moribund children. Note that if your forked child inherits system file descriptors like STDIN and STDOUT that are actually connected by a pipe or socket, even if you exit, then the remote server (such as, say, a CGI script or a backgrounded job launched from a remote shell) won't think you're done. You should reopen those to F</dev/null> if it's any issue. On some platforms such as Windows, where the fork() system call is not available, Perl can be built to emulate fork() in the Perl interpreter. The emulation is designed, at the level of the Perl program, to be as compatible as possible with the "Unix" fork(). However it has limitations that have to be considered in code intended to be portable. See L<perlfork> for more details. Portability issues: L<perlport/fork>. =item format X<format> =for Pod::Functions declare a picture format with use by the write() function Declare a picture format for use by the C<write> function. For example: format Something = Test: @<<<<<<<< @||||| @>>>>> $str, $%, '$' . int($num) . $str = "widget"; $num = $cost/$quantity; $~ = 'Something'; write; See L<perlform> for many details and examples. =item formline PICTURE,LIST X<formline> =for Pod::Functions internal function used for formats This is an internal function used by C<format>s, though you may call it, too. It formats (see L<perlform>) a list of values according to the contents of PICTURE, placing the output into the format output accumulator, C<$^A> (or C<$ACCUMULATOR> in English). Eventually, when a C<write> is done, the contents of C<$^A> are written to some filehandle. You could also read C<$^A> and then set C<$^A> back to C<"">. Note that a format typically does one C<formline> per line of form, but the C<formline> function itself doesn't care how many newlines are embedded in the PICTURE. This means that the C<~> and C<~~> tokens treat the entire PICTURE as a single line. You may therefore need to use multiple formlines to implement a single record format, just like the C<format> compiler. Be careful if you put double quotes around the picture, because an C<@> character may be taken to mean the beginning of an array name. C<formline> always returns true. See L<perlform> for other examples. If you are trying to use this instead of C<write> to capture the output, you may find it easier to open a filehandle to a scalar (C<< open $fh, ">", \$output >>) and write to that instead. =item getc FILEHANDLE X<getc> X<getchar> X<character> X<file, read> =item getc =for Pod::Functions get the next character from the filehandle Returns the next character from the input file attached to FILEHANDLE, or the undefined value at end of file or if there was an error (in the latter case C<$!> is set). If FILEHANDLE is omitted, reads from STDIN. This is not particularly efficient. However, it cannot be used by itself to fetch single characters without waiting for the user to hit enter. For that, try something more like: if ($BSD_STYLE) { system "stty cbreak </dev/tty >/dev/tty 2>&1"; } else { system "stty", '-icanon', 'eol', "\001"; } $key = getc(STDIN); if ($BSD_STYLE) { system "stty -cbreak </dev/tty >/dev/tty 2>&1"; } else { system 'stty', 'icanon', 'eol', '^@'; # ASCII NUL } print "\n"; Determination of whether $BSD_STYLE should be set is left as an exercise to the reader. The C<POSIX::getattr> function can do this more portably on systems purporting POSIX compliance. See also the C<Term::ReadKey> module from your nearest CPAN site; details on CPAN can be found under L<perlmodlib/CPAN>. =item getlogin X<getlogin> X<login> =for Pod::Functions return who logged in at this tty This implements the C library function of the same name, which on most systems returns the current login from F</etc/utmp>, if any. If it returns the empty string, use C<getpwuid>. $login = getlogin || getpwuid($<) || "Kilroy"; Do not consider C<getlogin> for authentication: it is not as secure as C<getpwuid>. Portability issues: L<perlport/getlogin>. =item getpeername SOCKET X<getpeername> X<peer> =for Pod::Functions find the other end of a socket connection Returns the packed sockaddr address of the other end of the SOCKET connection. use Socket; $hersockaddr = getpeername(SOCK); ($port, $iaddr) = sockaddr_in($hersockaddr); $herhostname = gethostbyaddr($iaddr, AF_INET); $herstraddr = inet_ntoa($iaddr); =item getpgrp PID X<getpgrp> X<group> =for Pod::Functions get process group Returns the current process group for the specified PID. Use a PID of C<0> to get the current process group for the current process. Will raise an exception if used on a machine that doesn't implement getpgrp(2). If PID is omitted, returns the process group of the current process. Note that the POSIX version of C<getpgrp> does not accept a PID argument, so only C<PID==0> is truly portable. Portability issues: L<perlport/getpgrp>. =item getppid X<getppid> X<parent> X<pid> =for Pod::Functions get parent process ID Returns the process id of the parent process. Note for Linux users: Between v5.8.1 and v5.16.0 Perl would work around non-POSIX thread semantics the minority of Linux systems (and Debian GNU/kFreeBSD systems) that used LinuxThreads, this emulation has since been removed. See the documentation for L<$$|perlvar/$$> for details. Portability issues: L<perlport/getppid>. =item getpriority WHICH,WHO X<getpriority> X<priority> X<nice> =for Pod::Functions get current nice value Returns the current priority for a process, a process group, or a user. (See L<getpriority(2)>.) Will raise a fatal exception if used on a machine that doesn't implement getpriority(2). Portability issues: L<perlport/getpriority>. =item getpwnam NAME X<getpwnam> X<getgrnam> X<gethostbyname> X<getnetbyname> X<getprotobyname> X<getpwuid> X<getgrgid> X<getservbyname> X<gethostbyaddr> X<getnetbyaddr> X<getprotobynumber> X<getservbyport> X<getpwent> X<getgrent> X<gethostent> X<getnetent> X<getprotoent> X<getservent> X<setpwent> X<setgrent> X<sethostent> X<setnetent> X<setprotoent> X<setservent> X<endpwent> X<endgrent> X<endhostent> X<endnetent> X<endprotoent> X<endservent> =for Pod::Functions get passwd record given user login name =item getgrnam NAME =for Pod::Functions get group record given group name =item gethostbyname NAME =for Pod::Functions get host record given name =item getnetbyname NAME =for Pod::Functions get networks record given name =item getprotobyname NAME =for Pod::Functions get protocol record given name =item getpwuid UID =for Pod::Functions get passwd record given user ID =item getgrgid GID =for Pod::Functions get group record given group user ID =item getservbyname NAME,PROTO =for Pod::Functions get services record given its name =item gethostbyaddr ADDR,ADDRTYPE =for Pod::Functions get host record given its address =item getnetbyaddr ADDR,ADDRTYPE =for Pod::Functions get network record given its address =item getprotobynumber NUMBER =for Pod::Functions get protocol record numeric protocol =item getservbyport PORT,PROTO =for Pod::Functions get services record given numeric port =item getpwent =for Pod::Functions get next passwd record =item getgrent =for Pod::Functions get next group record =item gethostent =for Pod::Functions get next hosts record =item getnetent =for Pod::Functions get next networks record =item getprotoent =for Pod::Functions get next protocols record =item getservent =for Pod::Functions get next services record =item setpwent =for Pod::Functions prepare passwd file for use =item setgrent =for Pod::Functions prepare group file for use =item sethostent STAYOPEN =for Pod::Functions prepare hosts file for use =item setnetent STAYOPEN =for Pod::Functions prepare networks file for use =item setprotoent STAYOPEN =for Pod::Functions prepare protocols file for use =item setservent STAYOPEN =for Pod::Functions prepare services file for use =item endpwent =for Pod::Functions be done using passwd file =item endgrent =for Pod::Functions be done using group file =item endhostent =for Pod::Functions be done using hosts file =item endnetent =for Pod::Functions be done using networks file =item endprotoent =for Pod::Functions be done using protocols file =item endservent =for Pod::Functions be done using services file These routines are the same as their counterparts in the system C library. In list context, the return values from the various get routines are as follows: ($name,$passwd,$uid,$gid, $quota,$comment,$gcos,$dir,$shell,$expire) = getpw* ($name,$passwd,$gid,$members) = getgr* ($name,$aliases,$addrtype,$length,@addrs) = gethost* ($name,$aliases,$addrtype,$net) = getnet* ($name,$aliases,$proto) = getproto* ($name,$aliases,$port,$proto) = getserv* (If the entry doesn't exist you get an empty list.) The exact meaning of the $gcos field varies but it usually contains the real name of the user (as opposed to the login name) and other information pertaining to the user. Beware, however, that in many system users are able to change this information and therefore it cannot be trusted and therefore the $gcos is tainted (see L<perlsec>). The $passwd and $shell, user's encrypted password and login shell, are also tainted, for the same reason. In scalar context, you get the name, unless the function was a lookup by name, in which case you get the other thing, whatever it is. (If the entry doesn't exist you get the undefined value.) For example: $uid = getpwnam($name); $name = getpwuid($num); $name = getpwent(); $gid = getgrnam($name); $name = getgrgid($num); $name = getgrent(); #etc. In I<getpw*()> the fields $quota, $comment, and $expire are special in that they are unsupported on many systems. If the $quota is unsupported, it is an empty scalar. If it is supported, it usually encodes the disk quota. If the $comment field is unsupported, it is an empty scalar. If it is supported it usually encodes some administrative comment about the user. In some systems the $quota field may be $change or $age, fields that have to do with password aging. In some systems the $comment field may be $class. The $expire field, if present, encodes the expiration period of the account or the password. For the availability and the exact meaning of these fields in your system, please consult getpwnam(3) and your system's F<pwd.h> file. You can also find out from within Perl what your $quota and $comment fields mean and whether you have the $expire field by using the C<Config> module and the values C<d_pwquota>, C<d_pwage>, C<d_pwchange>, C<d_pwcomment>, and C<d_pwexpire>. Shadow password files are supported only if your vendor has implemented them in the intuitive fashion that calling the regular C library routines gets the shadow versions if you're running under privilege or if there exists the shadow(3) functions as found in System V (this includes Solaris and Linux). Those systems that implement a proprietary shadow password facility are unlikely to be supported. The $members value returned by I<getgr*()> is a space-separated list of the login names of the members of the group. For the I<gethost*()> functions, if the C<h_errno> variable is supported in C, it will be returned to you via C<$?> if the function call fails. The C<@addrs> value returned by a successful call is a list of raw addresses returned by the corresponding library call. In the Internet domain, each address is four bytes long; you can unpack it by saying something like: ($a,$b,$c,$d) = unpack('W4',$addr[0]); The Socket library makes this slightly easier: use Socket; $iaddr = inet_aton("127.1"); # or whatever address $name = gethostbyaddr($iaddr, AF_INET); # or going the other way $straddr = inet_ntoa($iaddr); In the opposite way, to resolve a hostname to the IP address you can write this: use Socket; $packed_ip = gethostbyname("www.perl.org"); if (defined $packed_ip) { $ip_address = inet_ntoa($packed_ip); } Make sure C<gethostbyname()> is called in SCALAR context and that its return value is checked for definedness. The C<getprotobynumber> function, even though it only takes one argument, has the precedence of a list operator, so beware: getprotobynumber $number eq 'icmp' # WRONG getprotobynumber($number eq 'icmp') # actually means this getprotobynumber($number) eq 'icmp' # better this way If you get tired of remembering which element of the return list contains which return value, by-name interfaces are provided in standard modules: C<File::stat>, C<Net::hostent>, C<Net::netent>, C<Net::protoent>, C<Net::servent>, C<Time::gmtime>, C<Time::localtime>, and C<User::grent>. These override the normal built-ins, supplying versions that return objects with the appropriate names for each field. For example: use File::stat; use User::pwent; $is_his = (stat($filename)->uid == pwent($whoever)->uid); Even though it looks as though they're the same method calls (uid), they aren't, because a C<File::stat> object is different from a C<User::pwent> object. Portability issues: L<perlport/getpwnam> to L<perlport/endservent>. =item getsockname SOCKET X<getsockname> =for Pod::Functions retrieve the sockaddr for a given socket Returns the packed sockaddr address of this end of the SOCKET connection, in case you don't know the address because you have several different IPs that the connection might have come in on. use Socket; $mysockaddr = getsockname(SOCK); ($port, $myaddr) = sockaddr_in($mysockaddr); printf "Connect to %s [%s]\n", scalar gethostbyaddr($myaddr, AF_INET), inet_ntoa($myaddr); =item getsockopt SOCKET,LEVEL,OPTNAME X<getsockopt> =for Pod::Functions get socket options on a given socket Queries the option named OPTNAME associated with SOCKET at a given LEVEL. Options may exist at multiple protocol levels depending on the socket type, but at least the uppermost socket level SOL_SOCKET (defined in the C<Socket> module) will exist. To query options at another level the protocol number of the appropriate protocol controlling the option should be supplied. For example, to indicate that an option is to be interpreted by the TCP protocol, LEVEL should be set to the protocol number of TCP, which you can get using C<getprotobyname>. The function returns a packed string representing the requested socket option, or C<undef> on error, with the reason for the error placed in C<$!>. Just what is in the packed string depends on LEVEL and OPTNAME; consult getsockopt(2) for details. A common case is that the option is an integer, in which case the result is a packed integer, which you can decode using C<unpack> with the C<i> (or C<I>) format. Here's an example to test whether Nagle's algorithm is enabled on a socket: use Socket qw(:all); defined(my $tcp = getprotobyname("tcp")) or die "Could not determine the protocol number for tcp"; # my $tcp = IPPROTO_TCP; # Alternative my $packed = getsockopt($socket, $tcp, TCP_NODELAY) or die "getsockopt TCP_NODELAY: $!"; my $nodelay = unpack("I", $packed); print "Nagle's algorithm is turned ", $nodelay ? "off\n" : "on\n"; Portability issues: L<perlport/getsockopt>. =item glob EXPR X<glob> X<wildcard> X<filename, expansion> X<expand> =item glob =for Pod::Functions expand filenames using wildcards In list context, returns a (possibly empty) list of filename expansions on the value of EXPR such as the standard Unix shell F</bin/csh> would do. In scalar context, glob iterates through such filename expansions, returning undef when the list is exhausted. This is the internal function implementing the C<< <*.c> >> operator, but you can use it directly. If EXPR is omitted, C<$_> is used. The C<< <*.c> >> operator is discussed in more detail in L<perlop/"I/O Operators">. Note that C<glob> splits its arguments on whitespace and treats each segment as separate pattern. As such, C<glob("*.c *.h")> matches all files with a F<.c> or F<.h> extension. The expression C<glob(".* *")> matches all files in the current working directory. If you want to glob filenames that might contain whitespace, you'll have to use extra quotes around the spacey filename to protect it. For example, to glob filenames that have an C<e> followed by a space followed by an C<f>, use either of: @spacies = <"*e f*">; @spacies = glob '"*e f*"'; @spacies = glob q("*e f*"); If you had to get a variable through, you could do this: @spacies = glob "'*${var}e f*'"; @spacies = glob qq("*${var}e f*"); If non-empty braces are the only wildcard characters used in the C<glob>, no filenames are matched, but potentially many strings are returned. For example, this produces nine strings, one for each pairing of fruits and colors: @many = glob "{apple,tomato,cherry}={green,yellow,red}"; Beginning with v5.6.0, this operator is implemented using the standard C<File::Glob> extension. See L<File::Glob> for details, including C<bsd_glob> which does not treat whitespace as a pattern separator. Portability issues: L<perlport/glob>. =item gmtime EXPR X<gmtime> X<UTC> X<Greenwich> =item gmtime =for Pod::Functions convert UNIX time into record or string using Greenwich time Works just like L</localtime> but the returned values are localized for the standard Greenwich time zone. Note: When called in list context, $isdst, the last value returned by gmtime, is always C<0>. There is no Daylight Saving Time in GMT. Portability issues: L<perlport/gmtime>. =item goto LABEL X<goto> X<jump> X<jmp> =item goto EXPR =item goto &NAME =for Pod::Functions create spaghetti code The C<goto-LABEL> form finds the statement labeled with LABEL and resumes execution there. It can't be used to get out of a block or subroutine given to C<sort>. It can be used to go almost anywhere else within the dynamic scope, including out of subroutines, but it's usually better to use some other construct such as C<last> or C<die>. The author of Perl has never felt the need to use this form of C<goto> (in Perl, that is; C is another matter). (The difference is that C does not offer named loops combined with loop control. Perl does, and this replaces most structured uses of C<goto> in other languages.) The C<goto-EXPR> form expects a label name, whose scope will be resolved dynamically. This allows for computed C<goto>s per FORTRAN, but isn't necessarily recommended if you're optimizing for maintainability: goto ("FOO", "BAR", "GLARCH")[$i]; As shown in this example, C<goto-EXPR> is exempt from the "looks like a function" rule. A pair of parentheses following it does not (necessarily) delimit its argument. C<goto("NE")."XT"> is equivalent to C<goto NEXT>. Use of C<goto-LABEL> or C<goto-EXPR> to jump into a construct is deprecated and will issue a warning. Even then, it may not be used to go into any construct that requires initialization, such as a subroutine or a C<foreach> loop. It also can't be used to go into a construct that is optimized away. The C<goto-&NAME> form is quite different from the other forms of C<goto>. In fact, it isn't a goto in the normal sense at all, and doesn't have the stigma associated with other gotos. Instead, it exits the current subroutine (losing any changes set by local()) and immediately calls in its place the named subroutine using the current value of @_. This is used by C<AUTOLOAD> subroutines that wish to load another subroutine and then pretend that the other subroutine had been called in the first place (except that any modifications to C<@_> in the current subroutine are propagated to the other subroutine.) After the C<goto>, not even C<caller> will be able to tell that this routine was called first. NAME needn't be the name of a subroutine; it can be a scalar variable containing a code reference or a block that evaluates to a code reference. =item grep BLOCK LIST X<grep> =item grep EXPR,LIST =for Pod::Functions locate elements in a list test true against a given criterion This is similar in spirit to, but not the same as, grep(1) and its relatives. In particular, it is not limited to using regular expressions. Evaluates the BLOCK or EXPR for each element of LIST (locally setting C<$_> to each element) and returns the list value consisting of those elements for which the expression evaluated to true. In scalar context, returns the number of times the expression was true. @foo = grep(!/^#/, @bar); # weed out comments or equivalently, @foo = grep {!/^#/} @bar; # weed out comments Note that C<$_> is an alias to the list value, so it can be used to modify the elements of the LIST. While this is useful and supported, it can cause bizarre results if the elements of LIST are not variables. Similarly, grep returns aliases into the original list, much as a for loop's index variable aliases the list elements. That is, modifying an element of a list returned by grep (for example, in a C<foreach>, C<map> or another C<grep>) actually modifies the element in the original list. This is usually something to be avoided when writing clear code. If C<$_> is lexical in the scope where the C<grep> appears (because it has been declared with C<my $_>) then, in addition to being locally aliased to the list elements, C<$_> keeps being lexical inside the block; i.e., it can't be seen from the outside, avoiding any potential side-effects. See also L</map> for a list composed of the results of the BLOCK or EXPR. =item hex EXPR X<hex> X<hexadecimal> =item hex =for Pod::Functions convert a string to a hexadecimal number Interprets EXPR as a hex string and returns the corresponding value. (To convert strings that might start with either C<0>, C<0x>, or C<0b>, see L</oct>.) If EXPR is omitted, uses C<$_>. print hex '0xAf'; # prints '175' print hex 'aF'; # same Hex strings may only represent integers. Strings that would cause integer overflow trigger a warning. Leading whitespace is not stripped, unlike oct(). To present something as hex, look into L</printf>, L</sprintf>, and L</unpack>. =item import LIST X<import> =for Pod::Functions patch a module's namespace into your own There is no builtin C<import> function. It is just an ordinary method (subroutine) defined (or inherited) by modules that wish to export names to another module. The C<use> function calls the C<import> method for the package used. See also L</use>, L<perlmod>, and L<Exporter>. =item index STR,SUBSTR,POSITION X<index> X<indexOf> X<InStr> =item index STR,SUBSTR =for Pod::Functions find a substring within a string The index function searches for one string within another, but without the wildcard-like behavior of a full regular-expression pattern match. It returns the position of the first occurrence of SUBSTR in STR at or after POSITION. If POSITION is omitted, starts searching from the beginning of the string. POSITION before the beginning of the string or after its end is treated as if it were the beginning or the end, respectively. POSITION and the return value are based at zero. If the substring is not found, C<index> returns -1. =item int EXPR X<int> X<integer> X<truncate> X<trunc> X<floor> =item int =for Pod::Functions get the integer portion of a number Returns the integer portion of EXPR. If EXPR is omitted, uses C<$_>. You should not use this function for rounding: one because it truncates towards C<0>, and two because machine representations of floating-point numbers can sometimes produce counterintuitive results. For example, C<int(-6.725/0.025)> produces -268 rather than the correct -269; that's because it's really more like -268.99999999999994315658 instead. Usually, the C<sprintf>, C<printf>, or the C<POSIX::floor> and C<POSIX::ceil> functions will serve you better than will int(). =item ioctl FILEHANDLE,FUNCTION,SCALAR X<ioctl> =for Pod::Functions system-dependent device control system call Implements the ioctl(2) function. You'll probably first have to say require "sys/ioctl.ph"; # probably in $Config{archlib}/sys/ioctl.ph to get the correct function definitions. If F<sys/ioctl.ph> doesn't exist or doesn't have the correct definitions you'll have to roll your own, based on your C header files such as F<< <sys/ioctl.h> >>. (There is a Perl script called B<h2ph> that comes with the Perl kit that may help you in this, but it's nontrivial.) SCALAR will be read and/or written depending on the FUNCTION; a C pointer to the string value of SCALAR will be passed as the third argument of the actual C<ioctl> call. (If SCALAR has no string value but does have a numeric value, that value will be passed rather than a pointer to the string value. To guarantee this to be true, add a C<0> to the scalar before using it.) The C<pack> and C<unpack> functions may be needed to manipulate the values of structures used by C<ioctl>. The return value of C<ioctl> (and C<fcntl>) is as follows: if OS returns: then Perl returns: -1 undefined value 0 string "0 but true" anything else that number Thus Perl returns true on success and false on failure, yet you can still easily determine the actual value returned by the operating system: $retval = ioctl(...) || -1; printf "System returned %d\n", $retval; The special string C<"0 but true"> is exempt from B<-w> complaints about improper numeric conversions. Portability issues: L<perlport/ioctl>. =item join EXPR,LIST X<join> =for Pod::Functions join a list into a string using a separator Joins the separate strings of LIST into a single string with fields separated by the value of EXPR, and returns that new string. Example: $rec = join(':', $login,$passwd,$uid,$gid,$gcos,$home,$shell); Beware that unlike C<split>, C<join> doesn't take a pattern as its first argument. Compare L</split>. =item keys HASH X<keys> X<key> =item keys ARRAY =item keys EXPR =for Pod::Functions retrieve list of indices from a hash Called in list context, returns a list consisting of all the keys of the named hash, or in Perl 5.12 or later only, the indices of an array. Perl releases prior to 5.12 will produce a syntax error if you try to use an array argument. In scalar context, returns the number of keys or indices. The keys of a hash are returned in an apparently random order. The actual random order is subject to change in future versions of Perl, but it is guaranteed to be the same order as either the C<values> or C<each> function produces (given that the hash has not been modified). Since Perl 5.8.1 the ordering can be different even between different runs of Perl for security reasons (see L<perlsec/"Algorithmic Complexity Attacks">). As a side effect, calling keys() resets the internal interator of the HASH or ARRAY (see L</each>). In particular, calling keys() in void context resets the iterator with no other overhead. Here is yet another way to print your environment: @keys = keys %ENV; @values = values %ENV; while (@keys) { print pop(@keys), '=', pop(@values), "\n"; } or how about sorted by key: foreach $key (sort(keys %ENV)) { print $key, '=', $ENV{$key}, "\n"; } The returned values are copies of the original keys in the hash, so modifying them will not affect the original hash. Compare L</values>. To sort a hash by value, you'll need to use a C<sort> function. Here's a descending numeric sort of a hash by its values: foreach $key (sort { $hash{$b} <=> $hash{$a} } keys %hash) { printf "%4d %s\n", $hash{$key}, $key; } Used as an lvalue, C<keys> allows you to increase the number of hash buckets allocated for the given hash. This can gain you a measure of efficiency if you know the hash is going to get big. (This is similar to pre-extending an array by assigning a larger number to $#array.) If you say keys %hash = 200; then C<%hash> will have at least 200 buckets allocated for it--256 of them, in fact, since it rounds up to the next power of two. These buckets will be retained even if you do C<%hash = ()>, use C<undef %hash> if you want to free the storage while C<%hash> is still in scope. You can't shrink the number of buckets allocated for the hash using C<keys> in this way (but you needn't worry about doing this by accident, as trying has no effect). C<keys @array> in an lvalue context is a syntax error. Starting with Perl 5.14, C<keys> can take a scalar EXPR, which must contain a reference to an unblessed hash or array. The argument will be dereferenced automatically. This aspect of C<keys> is considered highly experimental. The exact behaviour may change in a future version of Perl. for (keys $hashref) { ... } for (keys $obj->get_arrayref) { ... } To avoid confusing would-be users of your code who are running earlier versions of Perl with mysterious syntax errors, put this sort of thing at the top of your file to signal that your code will work I<only> on Perls of a recent vintage: use 5.012; # so keys/values/each work on arrays use 5.014; # so keys/values/each work on scalars (experimental) See also C<each>, C<values>, and C<sort>. =item kill SIGNAL, LIST =item kill SIGNAL X<kill> X<signal> =for Pod::Functions send a signal to a process or process group Sends a signal to a list of processes. Returns the number of processes successfully signaled (which is not necessarily the same as the number actually killed). $cnt = kill 1, $child1, $child2; kill 9, @goners; If SIGNAL is zero, no signal is sent to the process, but C<kill> checks whether it's I<possible> to send a signal to it (that means, to be brief, that the process is owned by the same user, or we are the super-user). This is useful to check that a child process is still alive (even if only as a zombie) and hasn't changed its UID. See L<perlport> for notes on the portability of this construct. Unlike in the shell, if SIGNAL is negative, it kills process groups instead of processes. That means you usually want to use positive not negative signals. You may also use a signal name in quotes. The behavior of kill when a I<PROCESS> number is zero or negative depends on the operating system. For example, on POSIX-conforming systems, zero will signal the current process group and -1 will signal all processes. See L<perlipc/"Signals"> for more details. On some platforms such as Windows where the fork() system call is not available. Perl can be built to emulate fork() at the interpreter level. This emulation has limitations related to kill that have to be considered, for code running on Windows and in code intended to be portable. See L<perlfork> for more details. If there is no I<LIST> of processes, no signal is sent, and the return value is 0. This form is sometimes used, however, because it causes tainting checks to be run. But see L<perlsec/Laundering and Detecting Tainted Data>. Portability issues: L<perlport/kill>. =item last LABEL X<last> X<break> =item last =for Pod::Functions exit a block prematurely The C<last> command is like the C<break> statement in C (as used in loops); it immediately exits the loop in question. If the LABEL is omitted, the command refers to the innermost enclosing loop. The C<continue> block, if any, is not executed: LINE: while (<STDIN>) { last LINE if /^$/; # exit when done with header #... } C<last> cannot be used to exit a block that returns a value such as C<eval {}>, C<sub {}>, or C<do {}>, and should not be used to exit a grep() or map() operation. Note that a block by itself is semantically identical to a loop that executes once. Thus C<last> can be used to effect an early exit out of such a block. See also L</continue> for an illustration of how C<last>, C<next>, and C<redo> work. =item lc EXPR X<lc> X<lowercase> =item lc =for Pod::Functions return lower-case version of a string Returns a lowercased version of EXPR. This is the internal function implementing the C<\L> escape in double-quoted strings. If EXPR is omitted, uses C<$_>. What gets returned depends on several factors: =over =item If C<use bytes> is in effect: =over =item On EBCDIC platforms The results are what the C language system call C<tolower()> returns. =item On ASCII platforms The results follow ASCII semantics. Only characters C<A-Z> change, to C<a-z> respectively. =back =item Otherwise, if C<use locale> (but not C<use locale ':not_characters'>) is in effect: Respects current LC_CTYPE locale for code points < 256; and uses Unicode semantics for the remaining code points (this last can only happen if the UTF8 flag is also set). See L<perllocale>. A deficiency in this is that case changes that cross the 255/256 boundary are not well-defined. For example, the lower case of LATIN CAPITAL LETTER SHARP S (U+1E9E) in Unicode semantics is U+00DF (on ASCII platforms). But under C<use locale>, the lower case of U+1E9E is itself, because 0xDF may not be LATIN SMALL LETTER SHARP S in the current locale, and Perl has no way of knowing if that character even exists in the locale, much less what code point it is. Perl returns the input character unchanged, for all instances (and there aren't many) where the 255/256 boundary would otherwise be crossed. =item Otherwise, If EXPR has the UTF8 flag set: Unicode semantics are used for the case change. =item Otherwise, if C<use feature 'unicode_strings'> or C<use locale ':not_characters'>) is in effect: Unicode semantics are used for the case change. =item Otherwise: =over =item On EBCDIC platforms The results are what the C language system call C<tolower()> returns. =item On ASCII platforms ASCII semantics are used for the case change. The lowercase of any character outside the ASCII range is the character itself. =back =back =item lcfirst EXPR X<lcfirst> X<lowercase> =item lcfirst =for Pod::Functions return a string with just the next letter in lower case Returns the value of EXPR with the first character lowercased. This is the internal function implementing the C<\l> escape in double-quoted strings. If EXPR is omitted, uses C<$_>. This function behaves the same way under various pragmata, such as in a locale, as L</lc> does. =item length EXPR X<length> X<size> =item length =for Pod::Functions return the number of bytes in a string Returns the length in I<characters> of the value of EXPR. If EXPR is omitted, returns the length of C<$_>. If EXPR is undefined, returns C<undef>. This function cannot be used on an entire array or hash to find out how many elements these have. For that, use C<scalar @array> and C<scalar keys %hash>, respectively. Like all Perl character operations, length() normally deals in logical characters, not physical bytes. For how many bytes a string encoded as UTF-8 would take up, use C<length(Encode::encode_utf8(EXPR))> (you'll have to C<use Encode> first). See L<Encode> and L<perlunicode>. =item __LINE__ X<__LINE__> =for Pod::Functions the current source line number A special token that compiles to the current line number. =item link OLDFILE,NEWFILE X<link> =for Pod::Functions create a hard link in the filesystem Creates a new filename linked to the old filename. Returns true for success, false otherwise. Portability issues: L<perlport/link>. =item listen SOCKET,QUEUESIZE X<listen> =for Pod::Functions register your socket as a server Does the same thing that the listen(2) system call does. Returns true if it succeeded, false otherwise. See the example in L<perlipc/"Sockets: Client/Server Communication">. =item local EXPR X<local> =for Pod::Functions create a temporary value for a global variable (dynamic scoping) You really probably want to be using C<my> instead, because C<local> isn't what most people think of as "local". See L<perlsub/"Private Variables via my()"> for details. A local modifies the listed variables to be local to the enclosing block, file, or eval. If more than one value is listed, the list must be placed in parentheses. See L<perlsub/"Temporary Values via local()"> for details, including issues with tied arrays and hashes. The C<delete local EXPR> construct can also be used to localize the deletion of array/hash elements to the current block. See L<perlsub/"Localized deletion of elements of composite types">. =item localtime EXPR X<localtime> X<ctime> =item localtime =for Pod::Functions convert UNIX time into record or string using local time Converts a time as returned by the time function to a 9-element list with the time analyzed for the local time zone. Typically used as follows: # 0 1 2 3 4 5 6 7 8 ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time); All list elements are numeric and come straight out of the C `struct tm'. C<$sec>, C<$min>, and C<$hour> are the seconds, minutes, and hours of the specified time. C<$mday> is the day of the month and C<$mon> the month in the range C<0..11>, with 0 indicating January and 11 indicating December. This makes it easy to get a month name from a list: my @abbr = qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec ); print "$abbr[$mon] $mday"; # $mon=9, $mday=18 gives "Oct 18" C<$year> contains the number of years since 1900. To get a 4-digit year write: $year += 1900; To get the last two digits of the year (e.g., "01" in 2001) do: $year = sprintf("%02d", $year % 100); C<$wday> is the day of the week, with 0 indicating Sunday and 3 indicating Wednesday. C<$yday> is the day of the year, in the range C<0..364> (or C<0..365> in leap years.) C<$isdst> is true if the specified time occurs during Daylight Saving Time, false otherwise. If EXPR is omitted, C<localtime()> uses the current time (as returned by time(3)). In scalar context, C<localtime()> returns the ctime(3) value: $now_string = localtime; # e.g., "Thu Oct 13 04:54:34 1994" The format of this scalar value is B<not> locale-dependent but built into Perl. For GMT instead of local time use the L</gmtime> builtin. See also the C<Time::Local> module (for converting seconds, minutes, hours, and such back to the integer value returned by time()), and the L<POSIX> module's strftime(3) and mktime(3) functions. To get somewhat similar but locale-dependent date strings, set up your locale environment variables appropriately (please see L<perllocale>) and try for example: use POSIX qw(strftime); $now_string = strftime "%a %b %e %H:%M:%S %Y", localtime; # or for GMT formatted appropriately for your locale: $now_string = strftime "%a %b %e %H:%M:%S %Y", gmtime; Note that the C<%a> and C<%b>, the short forms of the day of the week and the month of the year, may not necessarily be three characters wide. The L<Time::gmtime> and L<Time::localtime> modules provide a convenient, by-name access mechanism to the gmtime() and localtime() functions, respectively. For a comprehensive date and time representation look at the L<DateTime> module on CPAN. Portability issues: L<perlport/localtime>. =item lock THING X<lock> =for Pod::Functions +5.005 get a thread lock on a variable, subroutine, or method This function places an advisory lock on a shared variable or referenced object contained in I<THING> until the lock goes out of scope. The value returned is the scalar itself, if the argument is a scalar, or a reference, if the argument is a hash, array or subroutine. lock() is a "weak keyword" : this means that if you've defined a function by this name (before any calls to it), that function will be called instead. If you are not under C<use threads::shared> this does nothing. See L<threads::shared>. =item log EXPR X<log> X<logarithm> X<e> X<ln> X<base> =item log =for Pod::Functions retrieve the natural logarithm for a number Returns the natural logarithm (base I<e>) of EXPR. If EXPR is omitted, returns the log of C<$_>. To get the log of another base, use basic algebra: The base-N log of a number is equal to the natural log of that number divided by the natural log of N. For example: sub log10 { my $n = shift; return log($n)/log(10); } See also L</exp> for the inverse operation. =item lstat FILEHANDLE X<lstat> =item lstat EXPR =item lstat DIRHANDLE =item lstat =for Pod::Functions stat a symbolic link Does the same thing as the C<stat> function (including setting the special C<_> filehandle) but stats a symbolic link instead of the file the symbolic link points to. If symbolic links are unimplemented on your system, a normal C<stat> is done. For much more detailed information, please see the documentation for C<stat>. If EXPR is omitted, stats C<$_>. Portability issues: L<perlport/lstat>. =item m// =for Pod::Functions match a string with a regular expression pattern The match operator. See L<perlop/"Regexp Quote-Like Operators">. =item map BLOCK LIST X<map> =item map EXPR,LIST =for Pod::Functions apply a change to a list to get back a new list with the changes Evaluates the BLOCK or EXPR for each element of LIST (locally setting C<$_> to each element) and returns the list value composed of the results of each such evaluation. In scalar context, returns the total number of elements so generated. Evaluates BLOCK or EXPR in list context, so each element of LIST may produce zero, one, or more elements in the returned value. @chars = map(chr, @numbers); translates a list of numbers to the corresponding characters. my @squares = map { $_ * $_ } @numbers; translates a list of numbers to their squared values. my @squares = map { $_ > 5 ? ($_ * $_) : () } @numbers; shows that number of returned elements can differ from the number of input elements. To omit an element, return an empty list (). This could also be achieved by writing my @squares = map { $_ * $_ } grep { $_ > 5 } @numbers; which makes the intention more clear. Map always returns a list, which can be assigned to a hash such that the elements become key/value pairs. See L<perldata> for more details. %hash = map { get_a_key_for($_) => $_ } @array; is just a funny way to write %hash = (); foreach (@array) { $hash{get_a_key_for($_)} = $_; } Note that C<$_> is an alias to the list value, so it can be used to modify the elements of the LIST. While this is useful and supported, it can cause bizarre results if the elements of LIST are not variables. Using a regular C<foreach> loop for this purpose would be clearer in most cases. See also L</grep> for an array composed of those items of the original list for which the BLOCK or EXPR evaluates to true. If C<$_> is lexical in the scope where the C<map> appears (because it has been declared with C<my $_>), then, in addition to being locally aliased to the list elements, C<$_> keeps being lexical inside the block; that is, it can't be seen from the outside, avoiding any potential side-effects. C<{> starts both hash references and blocks, so C<map { ...> could be either the start of map BLOCK LIST or map EXPR, LIST. Because Perl doesn't look ahead for the closing C<}> it has to take a guess at which it's dealing with based on what it finds just after the C<{>. Usually it gets it right, but if it doesn't it won't realize something is wrong until it gets to the C<}> and encounters the missing (or unexpected) comma. The syntax error will be reported close to the C<}>, but you'll need to change something near the C<{> such as using a unary C<+> to give Perl some help: %hash = map { "\L$_" => 1 } @array # perl guesses EXPR. wrong %hash = map { +"\L$_" => 1 } @array # perl guesses BLOCK. right %hash = map { ("\L$_" => 1) } @array # this also works %hash = map { lc($_) => 1 } @array # as does this. %hash = map +( lc($_) => 1 ), @array # this is EXPR and works! %hash = map ( lc($_), 1 ), @array # evaluates to (1, @array) or to force an anon hash constructor use C<+{>: @hashes = map +{ lc($_) => 1 }, @array # EXPR, so needs comma at end to get a list of anonymous hashes each with only one entry apiece. =item mkdir FILENAME,MASK X<mkdir> X<md> X<directory, create> =item mkdir FILENAME =item mkdir =for Pod::Functions create a directory Creates the directory specified by FILENAME, with permissions specified by MASK (as modified by C<umask>). If it succeeds it returns true; otherwise it returns false and sets C<$!> (errno). MASK defaults to 0777 if omitted, and FILENAME defaults to C<$_> if omitted. In general, it is better to create directories with a permissive MASK and let the user modify that with their C<umask> than it is to supply a restrictive MASK and give the user no way to be more permissive. The exceptions to this rule are when the file or directory should be kept private (mail files, for instance). The perlfunc(1) entry on C<umask> discusses the choice of MASK in more detail. Note that according to the POSIX 1003.1-1996 the FILENAME may have any number of trailing slashes. Some operating and filesystems do not get this right, so Perl automatically removes all trailing slashes to keep everyone happy. To recursively create a directory structure, look at the C<mkpath> function of the L<File::Path> module. =item msgctl ID,CMD,ARG X<msgctl> =for Pod::Functions SysV IPC message control operations Calls the System V IPC function msgctl(2). You'll probably have to say use IPC::SysV; first to get the correct constant definitions. If CMD is C<IPC_STAT>, then ARG must be a variable that will hold the returned C<msqid_ds> structure. Returns like C<ioctl>: the undefined value for error, C<"0 but true"> for zero, or the actual return value otherwise. See also L<perlipc/"SysV IPC"> and the documentation for C<IPC::SysV> and C<IPC::Semaphore>. Portability issues: L<perlport/msgctl>. =item msgget KEY,FLAGS X<msgget> =for Pod::Functions get SysV IPC message queue Calls the System V IPC function msgget(2). Returns the message queue id, or C<undef> on error. See also L<perlipc/"SysV IPC"> and the documentation for C<IPC::SysV> and C<IPC::Msg>. Portability issues: L<perlport/msgget>. =item msgrcv ID,VAR,SIZE,TYPE,FLAGS X<msgrcv> =for Pod::Functions receive a SysV IPC message from a message queue Calls the System V IPC function msgrcv to receive a message from message queue ID into variable VAR with a maximum message size of SIZE. Note that when a message is received, the message type as a native long integer will be the first thing in VAR, followed by the actual message. This packing may be opened with C<unpack("l! a*")>. Taints the variable. Returns true if successful, false on error. See also L<perlipc/"SysV IPC"> and the documentation for C<IPC::SysV> and C<IPC::SysV::Msg>. Portability issues: L<perlport/msgrcv>. =item msgsnd ID,MSG,FLAGS X<msgsnd> =for Pod::Functions send a SysV IPC message to a message queue Calls the System V IPC function msgsnd to send the message MSG to the message queue ID. MSG must begin with the native long integer message type, be followed by the length of the actual message, and then finally the message itself. This kind of packing can be achieved with C<pack("l! a*", $type, $message)>. Returns true if successful, false on error. See also the C<IPC::SysV> and C<IPC::SysV::Msg> documentation. Portability issues: L<perlport/msgsnd>. =item my EXPR X<my> =item my TYPE EXPR =item my EXPR : ATTRS =item my TYPE EXPR : ATTRS =for Pod::Functions declare and assign a local variable (lexical scoping) A C<my> declares the listed variables to be local (lexically) to the enclosing block, file, or C<eval>. If more than one value is listed, the list must be placed in parentheses. The exact semantics and interface of TYPE and ATTRS are still evolving. TYPE is currently bound to the use of the C<fields> pragma, and attributes are handled using the C<attributes> pragma, or starting from Perl 5.8.0 also via the C<Attribute::Handlers> module. See L<perlsub/"Private Variables via my()"> for details, and L<fields>, L<attributes>, and L<Attribute::Handlers>. =item next LABEL X<next> X<continue> =item next =for Pod::Functions iterate a block prematurely The C<next> command is like the C<continue> statement in C; it starts the next iteration of the loop: LINE: while (<STDIN>) { next LINE if /^#/; # discard comments #... } Note that if there were a C<continue> block on the above, it would get executed even on discarded lines. If LABEL is omitted, the command refers to the innermost enclosing loop. C<next> cannot be used to exit a block which returns a value such as C<eval {}>, C<sub {}>, or C<do {}>, and should not be used to exit a grep() or map() operation. Note that a block by itself is semantically identical to a loop that executes once. Thus C<next> will exit such a block early. See also L</continue> for an illustration of how C<last>, C<next>, and C<redo> work. =item no MODULE VERSION LIST X<no declarations> X<unimporting> =item no MODULE VERSION =item no MODULE LIST =item no MODULE =item no VERSION =for Pod::Functions unimport some module symbols or semantics at compile time See the C<use> function, of which C<no> is the opposite. =item oct EXPR X<oct> X<octal> X<hex> X<hexadecimal> X<binary> X<bin> =item oct =for Pod::Functions convert a string to an octal number Interprets EXPR as an octal string and returns the corresponding value. (If EXPR happens to start off with C<0x>, interprets it as a hex string. If EXPR starts off with C<0b>, it is interpreted as a binary string. Leading whitespace is ignored in all three cases.) The following will handle decimal, binary, octal, and hex in standard Perl notation: $val = oct($val) if $val =~ /^0/; If EXPR is omitted, uses C<$_>. To go the other way (produce a number in octal), use sprintf() or printf(): $dec_perms = (stat("filename"))[2] & 07777; $oct_perm_str = sprintf "%o", $perms; The oct() function is commonly used when a string such as C<644> needs to be converted into a file mode, for example. Although Perl automatically converts strings into numbers as needed, this automatic conversion assumes base 10. Leading white space is ignored without warning, as too are any trailing non-digits, such as a decimal point (C<oct> only handles non-negative integers, not negative integers or floating point). =item open FILEHANDLE,EXPR X<open> X<pipe> X<file, open> X<fopen> =item open FILEHANDLE,MODE,EXPR =item open FILEHANDLE,MODE,EXPR,LIST =item open FILEHANDLE,MODE,REFERENCE =item open FILEHANDLE =for Pod::Functions open a file, pipe, or descriptor Opens the file whose filename is given by EXPR, and associates it with FILEHANDLE. Simple examples to open a file for reading: open(my $fh, "<", "input.txt") or die "cannot open < input.txt: $!"; and for writing: open(my $fh, ">", "output.txt") or die "cannot open > output.txt: $!"; (The following is a comprehensive reference to open(): for a gentler introduction you may consider L<perlopentut>.) If FILEHANDLE is an undefined scalar variable (or array or hash element), a new filehandle is autovivified, meaning that the variable is assigned a reference to a newly allocated anonymous filehandle. Otherwise if FILEHANDLE is an expression, its value is the real filehandle. (This is considered a symbolic reference, so C<use strict "refs"> should I<not> be in effect.) If EXPR is omitted, the global (package) scalar variable of the same name as the FILEHANDLE contains the filename. (Note that lexical variables--those declared with C<my> or C<state>--will not work for this purpose; so if you're using C<my> or C<state>, specify EXPR in your call to open.) If three (or more) arguments are specified, the open mode (including optional encoding) in the second argument are distinct from the filename in the third. If MODE is C<< < >> or nothing, the file is opened for input. If MODE is C<< > >>, the file is opened for output, with existing files first being truncated ("clobbered") and nonexisting files newly created. If MODE is C<<< >> >>>, the file is opened for appending, again being created if necessary. You can put a C<+> in front of the C<< > >> or C<< < >> to indicate that you want both read and write access to the file; thus C<< +< >> is almost always preferred for read/write updates--the C<< +> >> mode would clobber the file first. You can't usually use either read-write mode for updating textfiles, since they have variable-length records. See the B<-i> switch in L<perlrun> for a better approach. The file is created with permissions of C<0666> modified by the process's C<umask> value. These various prefixes correspond to the fopen(3) modes of C<r>, C<r+>, C<w>, C<w+>, C<a>, and C<a+>. In the one- and two-argument forms of the call, the mode and filename should be concatenated (in that order), preferably separated by white space. You can--but shouldn't--omit the mode in these forms when that mode is C<< < >>. It is always safe to use the two-argument form of C<open> if the filename argument is a known literal. For three or more arguments if MODE is C<|->, the filename is interpreted as a command to which output is to be piped, and if MODE is C<-|>, the filename is interpreted as a command that pipes output to us. In the two-argument (and one-argument) form, one should replace dash (C<->) with the command. See L<perlipc/"Using open() for IPC"> for more examples of this. (You are not allowed to C<open> to a command that pipes both in I<and> out, but see L<IPC::Open2>, L<IPC::Open3>, and L<perlipc/"Bidirectional Communication with Another Process"> for alternatives.) In the form of pipe opens taking three or more arguments, if LIST is specified (extra arguments after the command name) then LIST becomes arguments to the command invoked if the platform supports it. The meaning of C<open> with more than three arguments for non-pipe modes is not yet defined, but experimental "layers" may give extra LIST arguments meaning. In the two-argument (and one-argument) form, opening C<< <- >> or C<-> opens STDIN and opening C<< >- >> opens STDOUT. You may (and usually should) use the three-argument form of open to specify I/O layers (sometimes referred to as "disciplines") to apply to the handle that affect how the input and output are processed (see L<open> and L<PerlIO> for more details). For example: open(my $fh, "<:encoding(UTF-8)", "filename") || die "can't open UTF-8 encoded filename: $!"; opens the UTF8-encoded file containing Unicode characters; see L<perluniintro>. Note that if layers are specified in the three-argument form, then default layers stored in ${^OPEN} (see L<perlvar>; usually set by the B<open> pragma or the switch B<-CioD>) are ignored. Those layers will also be ignored if you specifying a colon with no name following it. In that case the default layer for the operating system (:raw on Unix, :crlf on Windows) is used. Open returns nonzero on success, the undefined value otherwise. If the C<open> involved a pipe, the return value happens to be the pid of the subprocess. If you're running Perl on a system that distinguishes between text files and binary files, then you should check out L</binmode> for tips for dealing with this. The key distinction between systems that need C<binmode> and those that don't is their text file formats. Systems like Unix, Mac OS, and Plan 9, that end lines with a single character and encode that character in C as C<"\n"> do not need C<binmode>. The rest need it. When opening a file, it's seldom a good idea to continue if the request failed, so C<open> is frequently used with C<die>. Even if C<die> won't do what you want (say, in a CGI script, where you want to format a suitable error message (but there are modules that can help with that problem)) always check the return value from opening a file. As a special case the three-argument form with a read/write mode and the third argument being C<undef>: open(my $tmp, "+>", undef) or die ... opens a filehandle to an anonymous temporary file. Also using C<< +< >> works for symmetry, but you really should consider writing something to the temporary file first. You will need to seek() to do the reading. Since v5.8.0, Perl has built using PerlIO by default. Unless you've changed this (such as building Perl with C<Configure -Uuseperlio>), you can open filehandles directly to Perl scalars via: open($fh, ">", \$variable) || .. To (re)open C<STDOUT> or C<STDERR> as an in-memory file, close it first: close STDOUT; open(STDOUT, ">", \$variable) or die "Can't open STDOUT: $!"; General examples: $ARTICLE = 100; open(ARTICLE) or die "Can't find article $ARTICLE: $!\n"; while (<ARTICLE>) {... open(LOG, ">>/usr/spool/news/twitlog"); # (log is reserved) # if the open fails, output is discarded open(my $dbase, "+<", "dbase.mine") # open for update or die "Can't open 'dbase.mine' for update: $!"; open(my $dbase, "+<dbase.mine") # ditto or die "Can't open 'dbase.mine' for update: $!"; open(ARTICLE, "-|", "caesar <$article") # decrypt article or die "Can't start caesar: $!"; open(ARTICLE, "caesar <$article |") # ditto or die "Can't start caesar: $!"; open(EXTRACT, "|sort >Tmp$$") # $$ is our process id or die "Can't start sort: $!"; # in-memory files open(MEMORY, ">", \$var) or die "Can't open memory file: $!"; print MEMORY "foo!\n"; # output will appear in $var # process argument list of files along with any includes foreach $file (@ARGV) { process($file, "fh00"); } sub process { my($filename, $input) = @_; $input++; # this is a string increment unless (open($input, "<", $filename)) { print STDERR "Can't open $filename: $!\n"; return; } local $_; while (<$input>) { # note use of indirection if (/^#include "(.*)"/) { process($1, $input); next; } #... # whatever } } See L<perliol> for detailed info on PerlIO. You may also, in the Bourne shell tradition, specify an EXPR beginning with C<< >& >>, in which case the rest of the string is interpreted as the name of a filehandle (or file descriptor, if numeric) to be duped (as C<dup(2)>) and opened. You may use C<&> after C<< > >>, C<<< >> >>>, C<< < >>, C<< +> >>, C<<< +>> >>>, and C<< +< >>. The mode you specify should match the mode of the original filehandle. (Duping a filehandle does not take into account any existing contents of IO buffers.) If you use the three-argument form, then you can pass either a number, the name of a filehandle, or the normal "reference to a glob". Here is a script that saves, redirects, and restores C<STDOUT> and C<STDERR> using various methods: #!/usr/bin/perl open(my $oldout, ">&STDOUT") or die "Can't dup STDOUT: $!"; open(OLDERR, ">&", \*STDERR) or die "Can't dup STDERR: $!"; open(STDOUT, '>', "foo.out") or die "Can't redirect STDOUT: $!"; open(STDERR, ">&STDOUT") or die "Can't dup STDOUT: $!"; select STDERR; $| = 1; # make unbuffered select STDOUT; $| = 1; # make unbuffered print STDOUT "stdout 1\n"; # this works for print STDERR "stderr 1\n"; # subprocesses too open(STDOUT, ">&", $oldout) or die "Can't dup \$oldout: $!"; open(STDERR, ">&OLDERR") or die "Can't dup OLDERR: $!"; print STDOUT "stdout 2\n"; print STDERR "stderr 2\n"; If you specify C<< '<&=X' >>, where C<X> is a file descriptor number or a filehandle, then Perl will do an equivalent of C's C<fdopen> of that file descriptor (and not call C<dup(2)>); this is more parsimonious of file descriptors. For example: # open for input, reusing the fileno of $fd open(FILEHANDLE, "<&=$fd") or open(FILEHANDLE, "<&=", $fd) or # open for append, using the fileno of OLDFH open(FH, ">>&=", OLDFH) or open(FH, ">>&=OLDFH") Being parsimonious on filehandles is also useful (besides being parsimonious) for example when something is dependent on file descriptors, like for example locking using flock(). If you do just C<< open(A, ">>&B") >>, the filehandle A will not have the same file descriptor as B, and therefore flock(A) will not flock(B) nor vice versa. But with C<< open(A, ">>&=B") >>, the filehandles will share the same underlying system file descriptor. Note that under Perls older than 5.8.0, Perl uses the standard C library's' fdopen() to implement the C<=> functionality. On many Unix systems, fdopen() fails when file descriptors exceed a certain value, typically 255. For Perls 5.8.0 and later, PerlIO is (most often) the default. You can see whether your Perl was built with PerlIO by running C<perl -V> and looking for the C<useperlio=> line. If C<useperlio> is C<define>, you have PerlIO; otherwise you don't. If you open a pipe on the command C<-> (that is, specify either C<|-> or C<-|> with the one- or two-argument forms of C<open>), an implicit C<fork> is done, so C<open> returns twice: in the parent process it returns the pid of the child process, and in the child process it returns (a defined) C<0>. Use C<defined($pid)> or C<//> to determine whether the open was successful. For example, use either $child_pid = open(FROM_KID, "-|") // die "can't fork: $!"; or $child_pid = open(TO_KID, "|-") // die "can't fork: $!"; followed by if ($child_pid) { # am the parent: # either write TO_KID or else read FROM_KID ... wait $child_pid; } else { # am the child; use STDIN/STDOUT normally ... exit; } The filehandle behaves normally for the parent, but I/O to that filehandle is piped from/to the STDOUT/STDIN of the child process. In the child process, the filehandle isn't opened--I/O happens from/to the new STDOUT/STDIN. Typically this is used like the normal piped open when you want to exercise more control over just how the pipe command gets executed, such as when running setuid and you don't want to have to scan shell commands for metacharacters. The following blocks are more or less equivalent: open(FOO, "|tr '[a-z]' '[A-Z]'"); open(FOO, "|-", "tr '[a-z]' '[A-Z]'"); open(FOO, "|-") || exec 'tr', '[a-z]', '[A-Z]'; open(FOO, "|-", "tr", '[a-z]', '[A-Z]'); open(FOO, "cat -n '$file'|"); open(FOO, "-|", "cat -n '$file'"); open(FOO, "-|") || exec "cat", "-n", $file; open(FOO, "-|", "cat", "-n", $file); The last two examples in each block show the pipe as "list form", which is not yet supported on all platforms. A good rule of thumb is that if your platform has a real C<fork()> (in other words, if your platform is Unix, including Linux and MacOS X), you can use the list form. You would want to use the list form of the pipe so you can pass literal arguments to the command without risk of the shell interpreting any shell metacharacters in them. However, this also bars you from opening pipes to commands that intentionally contain shell metacharacters, such as: open(FOO, "|cat -n | expand -4 | lpr") // die "Can't open pipeline to lpr: $!"; See L<perlipc/"Safe Pipe Opens"> for more examples of this. Beginning with v5.6.0, Perl will attempt to flush all files opened for output before any operation that may do a fork, but this may not be supported on some platforms (see L<perlport>). To be safe, you may need to set C<$|> ($AUTOFLUSH in English) or call the C<autoflush()> method of C<IO::Handle> on any open handles. On systems that support a close-on-exec flag on files, the flag will be set for the newly opened file descriptor as determined by the value of C<$^F>. See L<perlvar/$^F>. Closing any piped filehandle causes the parent process to wait for the child to finish, then returns the status value in C<$?> and C<${^CHILD_ERROR_NATIVE}>. The filename passed to the one- and two-argument forms of open() will have leading and trailing whitespace deleted and normal redirection characters honored. This property, known as "magic open", can often be used to good effect. A user could specify a filename of F<"rsh cat file |">, or you could change certain filenames as needed: $filename =~ s/(.*\.gz)\s*$/gzip -dc < $1|/; open(FH, $filename) or die "Can't open $filename: $!"; Use the three-argument form to open a file with arbitrary weird characters in it, open(FOO, "<", $file) || die "can't open < $file: $!"; otherwise it's necessary to protect any leading and trailing whitespace: $file =~ s#^(\s)#./$1#; open(FOO, "< $file\0") || die "open failed: $!"; (this may not work on some bizarre filesystems). One should conscientiously choose between the I<magic> and I<three-argument> form of open(): open(IN, $ARGV[0]) || die "can't open $ARGV[0]: $!"; will allow the user to specify an argument of the form C<"rsh cat file |">, but will not work on a filename that happens to have a trailing space, while open(IN, "<", $ARGV[0]) || die "can't open < $ARGV[0]: $!"; will have exactly the opposite restrictions. If you want a "real" C C<open> (see L<open(2)> on your system), then you should use the C<sysopen> function, which involves no such magic (but may use subtly different filemodes than Perl open(), which is mapped to C fopen()). This is another way to protect your filenames from interpretation. For example: use IO::Handle; sysopen(HANDLE, $path, O_RDWR|O_CREAT|O_EXCL) or die "sysopen $path: $!"; $oldfh = select(HANDLE); $| = 1; select($oldfh); print HANDLE "stuff $$\n"; seek(HANDLE, 0, 0); print "File contains: ", <HANDLE>; Using the constructor from the C<IO::Handle> package (or one of its subclasses, such as C<IO::File> or C<IO::Socket>), you can generate anonymous filehandles that have the scope of the variables used to hold them, then automatically (but silently) close once their reference counts become zero, typically at scope exit: use IO::File; #... sub read_myfile_munged { my $ALL = shift; # or just leave it undef to autoviv my $handle = IO::File->new; open($handle, "<", "myfile") or die "myfile: $!"; $first = <$handle> or return (); # Automatically closed here. mung($first) or die "mung failed"; # Or here. return (first, <$handle>) if $ALL; # Or here. return $first; # Or here. } B<WARNING:> The previous example has a bug because the automatic close that happens when the refcount on C<handle> does not properly detect and report failures. I<Always> close the handle yourself and inspect the return value. close($handle) || warn "close failed: $!"; See L</seek> for some details about mixing reading and writing. Portability issues: L<perlport/open>. =item opendir DIRHANDLE,EXPR X<opendir> =for Pod::Functions open a directory Opens a directory named EXPR for processing by C<readdir>, C<telldir>, C<seekdir>, C<rewinddir>, and C<closedir>. Returns true if successful. DIRHANDLE may be an expression whose value can be used as an indirect dirhandle, usually the real dirhandle name. If DIRHANDLE is an undefined scalar variable (or array or hash element), the variable is assigned a reference to a new anonymous dirhandle; that is, it's autovivified. DIRHANDLEs have their own namespace separate from FILEHANDLEs. See the example at C<readdir>. =item ord EXPR X<ord> X<encoding> =item ord =for Pod::Functions find a character's numeric representation Returns the numeric value of the first character of EXPR. If EXPR is an empty string, returns 0. If EXPR is omitted, uses C<$_>. (Note I<character>, not byte.) For the reverse, see L</chr>. See L<perlunicode> for more about Unicode. =item our EXPR X<our> X<global> =item our TYPE EXPR =item our EXPR : ATTRS =item our TYPE EXPR : ATTRS =for Pod::Functions +5.6.0 declare and assign a package variable (lexical scoping) C<our> associates a simple name with a package variable in the current package for use within the current scope. When C<use strict 'vars'> is in effect, C<our> lets you use declared global variables without qualifying them with package names, within the lexical scope of the C<our> declaration. In this way C<our> differs from C<use vars>, which is package-scoped. Unlike C<my> or C<state>, which allocates storage for a variable and associates a simple name with that storage for use within the current scope, C<our> associates a simple name with a package (read: global) variable in the current package, for use within the current lexical scope. In other words, C<our> has the same scoping rules as C<my> or C<state>, but does not necessarily create a variable. If more than one value is listed, the list must be placed in parentheses. our $foo; our($bar, $baz); An C<our> declaration declares a global variable that will be visible across its entire lexical scope, even across package boundaries. The package in which the variable is entered is determined at the point of the declaration, not at the point of use. This means the following behavior holds: package Foo; our $bar; # declares $Foo::bar for rest of lexical scope $bar = 20; package Bar; print $bar; # prints 20, as it refers to $Foo::bar Multiple C<our> declarations with the same name in the same lexical scope are allowed if they are in different packages. If they happen to be in the same package, Perl will emit warnings if you have asked for them, just like multiple C<my> declarations. Unlike a second C<my> declaration, which will bind the name to a fresh variable, a second C<our> declaration in the same package, in the same scope, is merely redundant. use warnings; package Foo; our $bar; # declares $Foo::bar for rest of lexical scope $bar = 20; package Bar; our $bar = 30; # declares $Bar::bar for rest of lexical scope print $bar; # prints 30 our $bar; # emits warning but has no other effect print $bar; # still prints 30 An C<our> declaration may also have a list of attributes associated with it. The exact semantics and interface of TYPE and ATTRS are still evolving. TYPE is currently bound to the use of the C<fields> pragma, and attributes are handled using the C<attributes> pragma, or, starting from Perl 5.8.0, also via the C<Attribute::Handlers> module. See L<perlsub/"Private Variables via my()"> for details, and L<fields>, L<attributes>, and L<Attribute::Handlers>. =item pack TEMPLATE,LIST X<pack> =for Pod::Functions convert a list into a binary representation Takes a LIST of values and converts it into a string using the rules given by the TEMPLATE. The resulting string is the concatenation of the converted values. Typically, each converted value looks like its machine-level representation. For example, on 32-bit machines an integer may be represented by a sequence of 4 bytes, which will in Perl be presented as a string that's 4 characters long. See L<perlpacktut> for an introduction to this function. The TEMPLATE is a sequence of characters that give the order and type of values, as follows: a A string with arbitrary binary data, will be null padded. A A text (ASCII) string, will be space padded. Z A null-terminated (ASCIZ) string, will be null padded. b A bit string (ascending bit order inside each byte, like vec()). B A bit string (descending bit order inside each byte). h A hex string (low nybble first). H A hex string (high nybble first). c A signed char (8-bit) value. C An unsigned char (octet) value. W An unsigned char value (can be greater than 255). s A signed short (16-bit) value. S An unsigned short value. l A signed long (32-bit) value. L An unsigned long value. q A signed quad (64-bit) value. Q An unsigned quad value. (Quads are available only if your system supports 64-bit integer values _and_ if Perl has been compiled to support those. Raises an exception otherwise.) i A signed integer value. I A unsigned integer value. (This 'integer' is _at_least_ 32 bits wide. Its exact size depends on what a local C compiler calls 'int'.) n An unsigned short (16-bit) in "network" (big-endian) order. N An unsigned long (32-bit) in "network" (big-endian) order. v An unsigned short (16-bit) in "VAX" (little-endian) order. V An unsigned long (32-bit) in "VAX" (little-endian) order. j A Perl internal signed integer value (IV). J A Perl internal unsigned integer value (UV). f A single-precision float in native format. d A double-precision float in native format. F A Perl internal floating-point value (NV) in native format D A float of long-double precision in native format. (Long doubles are available only if your system supports long double values _and_ if Perl has been compiled to support those. Raises an exception otherwise.) p A pointer to a null-terminated string. P A pointer to a structure (fixed-length string). u A uuencoded string. U A Unicode character number. Encodes to a character in char- acter mode and UTF-8 (or UTF-EBCDIC in EBCDIC platforms) in byte mode. w A BER compressed integer (not an ASN.1 BER, see perlpacktut for details). Its bytes represent an unsigned integer in base 128, most significant digit first, with as few digits as possible. Bit eight (the high bit) is set on each byte except the last. x A null byte (a.k.a ASCII NUL, "\000", chr(0)) X Back up a byte. @ Null-fill or truncate to absolute position, counted from the start of the innermost ()-group. . Null-fill or truncate to absolute position specified by the value. ( Start of a ()-group. One or more modifiers below may optionally follow certain letters in the TEMPLATE (the second column lists letters for which the modifier is valid): ! sSlLiI Forces native (short, long, int) sizes instead of fixed (16-/32-bit) sizes. xX Make x and X act as alignment commands. nNvV Treat integers as signed instead of unsigned. @. Specify position as byte offset in the internal representation of the packed string. Efficient but dangerous. > sSiIlLqQ Force big-endian byte-order on the type. jJfFdDpP (The "big end" touches the construct.) < sSiIlLqQ Force little-endian byte-order on the type. jJfFdDpP (The "little end" touches the construct.) The C<< > >> and C<< < >> modifiers can also be used on C<()> groups to force a particular byte-order on all components in that group, including all its subgroups. The following rules apply: =over =item * Each letter may optionally be followed by a number indicating the repeat count. A numeric repeat count may optionally be enclosed in brackets, as in C<pack("C[80]", @arr)>. The repeat count gobbles that many values from the LIST when used with all format types other than C<a>, C<A>, C<Z>, C<b>, C<B>, C<h>, C<H>, C<@>, C<.>, C<x>, C<X>, and C<P>, where it means something else, described below. Supplying a C<*> for the repeat count instead of a number means to use however many items are left, except for: =over =item * C<@>, C<x>, and C<X>, where it is equivalent to C<0>. =item * <.>, where it means relative to the start of the string. =item * C<u>, where it is equivalent to 1 (or 45, which here is equivalent). =back One can replace a numeric repeat count with a template letter enclosed in brackets to use the packed byte length of the bracketed template for the repeat count. For example, the template C<x[L]> skips as many bytes as in a packed long, and the template C<"$t X[$t] $t"> unpacks twice whatever $t (when variable-expanded) unpacks. If the template in brackets contains alignment commands (such as C<x![d]>), its packed length is calculated as if the start of the template had the maximal possible alignment. When used with C<Z>, a C<*> as the repeat count is guaranteed to add a trailing null byte, so the resulting string is always one byte longer than the byte length of the item itself. When used with C<@>, the repeat count represents an offset from the start of the innermost C<()> group. When used with C<.>, the repeat count determines the starting position to calculate the value offset as follows: =over =item * If the repeat count is C<0>, it's relative to the current position. =item * If the repeat count is C<*>, the offset is relative to the start of the packed string. =item * And if it's an integer I<n>, the offset is relative to the start of the I<n>th innermost C<( )> group, or to the start of the string if I<n> is bigger then the group level. =back The repeat count for C<u> is interpreted as the maximal number of bytes to encode per line of output, with 0, 1 and 2 replaced by 45. The repeat count should not be more than 65. =item * The C<a>, C<A>, and C<Z> types gobble just one value, but pack it as a string of length count, padding with nulls or spaces as needed. When unpacking, C<A> strips trailing whitespace and nulls, C<Z> strips everything after the first null, and C<a> returns data with no stripping at all. If the value to pack is too long, the result is truncated. If it's too long and an explicit count is provided, C<Z> packs only C<$count-1> bytes, followed by a null byte. Thus C<Z> always packs a trailing null, except when the count is 0. =item * Likewise, the C<b> and C<B> formats pack a string that's that many bits long. Each such format generates 1 bit of the result. These are typically followed by a repeat count like C<B8> or C<B64>. Each result bit is based on the least-significant bit of the corresponding input character, i.e., on C<ord($char)%2>. In particular, characters C<"0"> and C<"1"> generate bits 0 and 1, as do characters C<"\000"> and C<"\001">. Starting from the beginning of the input string, each 8-tuple of characters is converted to 1 character of output. With format C<b>, the first character of the 8-tuple determines the least-significant bit of a character; with format C<B>, it determines the most-significant bit of a character. If the length of the input string is not evenly divisible by 8, the remainder is packed as if the input string were padded by null characters at the end. Similarly during unpacking, "extra" bits are ignored. If the input string is longer than needed, remaining characters are ignored. A C<*> for the repeat count uses all characters of the input field. On unpacking, bits are converted to a string of C<0>s and C<1>s. =item * The C<h> and C<H> formats pack a string that many nybbles (4-bit groups, representable as hexadecimal digits, C<"0".."9"> C<"a".."f">) long. For each such format, pack() generates 4 bits of result. With non-alphabetical characters, the result is based on the 4 least-significant bits of the input character, i.e., on C<ord($char)%16>. In particular, characters C<"0"> and C<"1"> generate nybbles 0 and 1, as do bytes C<"\000"> and C<"\001">. For characters C<"a".."f"> and C<"A".."F">, the result is compatible with the usual hexadecimal digits, so that C<"a"> and C<"A"> both generate the nybble C<0xA==10>. Use only these specific hex characters with this format. Starting from the beginning of the template to pack(), each pair of characters is converted to 1 character of output. With format C<h>, the first character of the pair determines the least-significant nybble of the output character; with format C<H>, it determines the most-significant nybble. If the length of the input string is not even, it behaves as if padded by a null character at the end. Similarly, "extra" nybbles are ignored during unpacking. If the input string is longer than needed, extra characters are ignored. A C<*> for the repeat count uses all characters of the input field. For unpack(), nybbles are converted to a string of hexadecimal digits. =item * The C<p> format packs a pointer to a null-terminated string. You are responsible for ensuring that the string is not a temporary value, as that could potentially get deallocated before you got around to using the packed result. The C<P> format packs a pointer to a structure of the size indicated by the length. A null pointer is created if the corresponding value for C<p> or C<P> is C<undef>; similarly with unpack(), where a null pointer unpacks into C<undef>. If your system has a strange pointer size--meaning a pointer is neither as big as an int nor as big as a long--it may not be possible to pack or unpack pointers in big- or little-endian byte order. Attempting to do so raises an exception. =item * The C</> template character allows packing and unpacking of a sequence of items where the packed structure contains a packed item count followed by the packed items themselves. This is useful when the structure you're unpacking has encoded the sizes or repeat counts for some of its fields within the structure itself as separate fields. For C<pack>, you write I<length-item>C</>I<sequence-item>, and the I<length-item> describes how the length value is packed. Formats likely to be of most use are integer-packing ones like C<n> for Java strings, C<w> for ASN.1 or SNMP, and C<N> for Sun XDR. For C<pack>, I<sequence-item> may have a repeat count, in which case the minimum of that and the number of available items is used as the argument for I<length-item>. If it has no repeat count or uses a '*', the number of available items is used. For C<unpack>, an internal stack of integer arguments unpacked so far is used. You write C</>I<sequence-item> and the repeat count is obtained by popping off the last element from the stack. The I<sequence-item> must not have a repeat count. If I<sequence-item> refers to a string type (C<"A">, C<"a">, or C<"Z">), the I<length-item> is the string length, not the number of strings. With an explicit repeat count for pack, the packed string is adjusted to that length. For example: This code: gives this result: unpack("W/a", "\004Gurusamy") ("Guru") unpack("a3/A A*", "007 Bond J ") (" Bond", "J") unpack("a3 x2 /A A*", "007: Bond, J.") ("Bond, J", ".") pack("n/a* w/a","hello,","world") "\000\006hello,\005world" pack("a/W2", ord("a") .. ord("z")) "2ab" The I<length-item> is not returned explicitly from C<unpack>. Supplying a count to the I<length-item> format letter is only useful with C<A>, C<a>, or C<Z>. Packing with a I<length-item> of C<a> or C<Z> may introduce C<"\000"> characters, which Perl does not regard as legal in numeric strings. =item * The integer types C<s>, C<S>, C<l>, and C<L> may be followed by a C<!> modifier to specify native shorts or longs. As shown in the example above, a bare C<l> means exactly 32 bits, although the native C<long> as seen by the local C compiler may be larger. This is mainly an issue on 64-bit platforms. You can see whether using C<!> makes any difference this way: printf "format s is %d, s! is %d\n", length pack("s"), length pack("s!"); printf "format l is %d, l! is %d\n", length pack("l"), length pack("l!"); C<i!> and C<I!> are also allowed, but only for completeness' sake: they are identical to C<i> and C<I>. The actual sizes (in bytes) of native shorts, ints, longs, and long longs on the platform where Perl was built are also available from the command line: $ perl -V:{short,int,long{,long}}size shortsize='2'; intsize='4'; longsize='4'; longlongsize='8'; or programmatically via the C<Config> module: use Config; print $Config{shortsize}, "\n"; print $Config{intsize}, "\n"; print $Config{longsize}, "\n"; print $Config{longlongsize}, "\n"; C<$Config{longlongsize}> is undefined on systems without long long support. =item * The integer formats C<s>, C<S>, C<i>, C<I>, C<l>, C<L>, C<j>, and C<J> are inherently non-portable between processors and operating systems because they obey native byteorder and endianness. For example, a 4-byte integer 0x12345678 (305419896 decimal) would be ordered natively (arranged in and handled by the CPU registers) into bytes as 0x12 0x34 0x56 0x78 # big-endian 0x78 0x56 0x34 0x12 # little-endian Basically, Intel and VAX CPUs are little-endian, while everybody else, including Motorola m68k/88k, PPC, Sparc, HP PA, Power, and Cray, are big-endian. Alpha and MIPS can be either: Digital/Compaq uses (well, used) them in little-endian mode, but SGI/Cray uses them in big-endian mode. The names I<big-endian> and I<little-endian> are comic references to the egg-eating habits of the little-endian Lilliputians and the big-endian Blefuscudians from the classic Jonathan Swift satire, I<Gulliver's Travels>. This entered computer lingo via the paper "On Holy Wars and a Plea for Peace" by Danny Cohen, USC/ISI IEN 137, April 1, 1980. Some systems may have even weirder byte orders such as 0x56 0x78 0x12 0x34 0x34 0x12 0x78 0x56 You can determine your system endianness with this incantation: printf("%#02x ", $_) for unpack("W*", pack L=>0x12345678); The byteorder on the platform where Perl was built is also available via L<Config>: use Config; print "$Config{byteorder}\n"; or from the command line: $ perl -V:byteorder Byteorders C<"1234"> and C<"12345678"> are little-endian; C<"4321"> and C<"87654321"> are big-endian. For portably packed integers, either use the formats C<n>, C<N>, C<v>, and C<V> or else use the C<< > >> and C<< < >> modifiers described immediately below. See also L<perlport>. =item * Starting with Perl 5.9.2, integer and floating-point formats, along with the C<p> and C<P> formats and C<()> groups, may all be followed by the C<< > >> or C<< < >> endianness modifiers to respectively enforce big- or little-endian byte-order. These modifiers are especially useful given how C<n>, C<N>, C<v>, and C<V> don't cover signed integers, 64-bit integers, or floating-point values. Here are some concerns to keep in mind when using an endianness modifier: =over =item * Exchanging signed integers between different platforms works only when all platforms store them in the same format. Most platforms store signed integers in two's-complement notation, so usually this is not an issue. =item * The C<< > >> or C<< < >> modifiers can only be used on floating-point formats on big- or little-endian machines. Otherwise, attempting to use them raises an exception. =item * Forcing big- or little-endian byte-order on floating-point values for data exchange can work only if all platforms use the same binary representation such as IEEE floating-point. Even if all platforms are using IEEE, there may still be subtle differences. Being able to use C<< > >> or C<< < >> on floating-point values can be useful, but also dangerous if you don't know exactly what you're doing. It is not a general way to portably store floating-point values. =item * When using C<< > >> or C<< < >> on a C<()> group, this affects all types inside the group that accept byte-order modifiers, including all subgroups. It is silently ignored for all other types. You are not allowed to override the byte-order within a group that already has a byte-order modifier suffix. =back =item * Real numbers (floats and doubles) are in native machine format only. Due to the multiplicity of floating-point formats and the lack of a standard "network" representation for them, no facility for interchange has been made. This means that packed floating-point data written on one machine may not be readable on another, even if both use IEEE floating-point arithmetic (because the endianness of the memory representation is not part of the IEEE spec). See also L<perlport>. If you know I<exactly> what you're doing, you can use the C<< > >> or C<< < >> modifiers to force big- or little-endian byte-order on floating-point values. Because Perl uses doubles (or long doubles, if configured) internally for all numeric calculation, converting from double into float and thence to double again loses precision, so C<unpack("f", pack("f", $foo)>) will not in general equal $foo. =item * Pack and unpack can operate in two modes: character mode (C<C0> mode) where the packed string is processed per character, and UTF-8 mode (C<U0> mode) where the packed string is processed in its UTF-8-encoded Unicode form on a byte-by-byte basis. Character mode is the default unless the format string starts with C<U>. You can always switch mode mid-format with an explicit C<C0> or C<U0> in the format. This mode remains in effect until the next mode change, or until the end of the C<()> group it (directly) applies to. Using C<C0> to get Unicode characters while using C<U0> to get I<non>-Unicode bytes is not necessarily obvious. Probably only the first of these is what you want: $ perl -CS -E 'say "\x{3B1}\x{3C9}"' | perl -CS -ne 'printf "%v04X\n", $_ for unpack("C0A*", $_)' 03B1.03C9 $ perl -CS -E 'say "\x{3B1}\x{3C9}"' | perl -CS -ne 'printf "%v02X\n", $_ for unpack("U0A*", $_)' CE.B1.CF.89 $ perl -CS -E 'say "\x{3B1}\x{3C9}"' | perl -C0 -ne 'printf "%v02X\n", $_ for unpack("C0A*", $_)' CE.B1.CF.89 $ perl -CS -E 'say "\x{3B1}\x{3C9}"' | perl -C0 -ne 'printf "%v02X\n", $_ for unpack("U0A*", $_)' C3.8E.C2.B1.C3.8F.C2.89 Those examples also illustrate that you should not try to use C<pack>/C<unpack> as a substitute for the L<Encode> module. =item * You must yourself do any alignment or padding by inserting, for example, enough C<"x">es while packing. There is no way for pack() and unpack() to know where characters are going to or coming from, so they handle their output and input as flat sequences of characters. =item * A C<()> group is a sub-TEMPLATE enclosed in parentheses. A group may take a repeat count either as postfix, or for unpack(), also via the C</> template character. Within each repetition of a group, positioning with C<@> starts over at 0. Therefore, the result of pack("@1A((@2A)@3A)", qw[X Y Z]) is the string C<"\0X\0\0YZ">. =item * C<x> and C<X> accept the C<!> modifier to act as alignment commands: they jump forward or back to the closest position aligned at a multiple of C<count> characters. For example, to pack() or unpack() a C structure like struct { char c; /* one signed, 8-bit character */ double d; char cc[2]; } one may need to use the template C<c x![d] d c[2]>. This assumes that doubles must be aligned to the size of double. For alignment commands, a C<count> of 0 is equivalent to a C<count> of 1; both are no-ops. =item * C<n>, C<N>, C<v> and C<V> accept the C<!> modifier to represent signed 16-/32-bit integers in big-/little-endian order. This is portable only when all platforms sharing packed data use the same binary representation for signed integers; for example, when all platforms use two's-complement representation. =item * Comments can be embedded in a TEMPLATE using C<#> through the end of line. White space can separate pack codes from each other, but modifiers and repeat counts must follow immediately. Breaking complex templates into individual line-by-line components, suitably annotated, can do as much to improve legibility and maintainability of pack/unpack formats as C</x> can for complicated pattern matches. =item * If TEMPLATE requires more arguments than pack() is given, pack() assumes additional C<""> arguments. If TEMPLATE requires fewer arguments than given, extra arguments are ignored. =back Examples: $foo = pack("WWWW",65,66,67,68); # foo eq "ABCD" $foo = pack("W4",65,66,67,68); # same thing $foo = pack("W4",0x24b6,0x24b7,0x24b8,0x24b9); # same thing with Unicode circled letters. $foo = pack("U4",0x24b6,0x24b7,0x24b8,0x24b9); # same thing with Unicode circled letters. You don't get the # UTF-8 bytes because the U at the start of the format caused # a switch to U0-mode, so the UTF-8 bytes get joined into # characters $foo = pack("C0U4",0x24b6,0x24b7,0x24b8,0x24b9); # foo eq "\xe2\x92\xb6\xe2\x92\xb7\xe2\x92\xb8\xe2\x92\xb9" # This is the UTF-8 encoding of the string in the # previous example $foo = pack("ccxxcc",65,66,67,68); # foo eq "AB\0\0CD" # NOTE: The examples above featuring "W" and "c" are true # only on ASCII and ASCII-derived systems such as ISO Latin 1 # and UTF-8. On EBCDIC systems, the first example would be # $foo = pack("WWWW",193,194,195,196); $foo = pack("s2",1,2); # "\001\000\002\000" on little-endian # "\000\001\000\002" on big-endian $foo = pack("a4","abcd","x","y","z"); # "abcd" $foo = pack("aaaa","abcd","x","y","z"); # "axyz" $foo = pack("a14","abcdefg"); # "abcdefg\0\0\0\0\0\0\0" $foo = pack("i9pl", gmtime); # a real struct tm (on my system anyway) $utmp_template = "Z8 Z8 Z16 L"; $utmp = pack($utmp_template, @utmp1); # a struct utmp (BSDish) @utmp2 = unpack($utmp_template, $utmp); # "@utmp1" eq "@utmp2" sub bintodec { unpack("N", pack("B32", substr("0" x 32 . shift, -32))); } $foo = pack('sx2l', 12, 34); # short 12, two zero bytes padding, long 34 $bar = pack('s@4l', 12, 34); # short 12, zero fill to position 4, long 34 # $foo eq $bar $baz = pack('s.l', 12, 4, 34); # short 12, zero fill to position 4, long 34 $foo = pack('nN', 42, 4711); # pack big-endian 16- and 32-bit unsigned integers $foo = pack('S>L>', 42, 4711); # exactly the same $foo = pack('s<l<', -42, 4711); # pack little-endian 16- and 32-bit signed integers $foo = pack('(sl)<', -42, 4711); # exactly the same The same template may generally also be used in unpack(). =item package NAMESPACE =item package NAMESPACE VERSION X<package> X<module> X<namespace> X<version> =item package NAMESPACE BLOCK =item package NAMESPACE VERSION BLOCK X<package> X<module> X<namespace> X<version> =for Pod::Functions declare a separate global namespace Declares the BLOCK or the rest of the compilation unit as being in the given namespace. The scope of the package declaration is either the supplied code BLOCK or, in the absence of a BLOCK, from the declaration itself through the end of current scope (the enclosing block, file, or C<eval>). That is, the forms without a BLOCK are operative through the end of the current scope, just like the C<my>, C<state>, and C<our> operators. All unqualified dynamic identifiers in this scope will be in the given namespace, except where overridden by another C<package> declaration or when they're one of the special identifiers that qualify into C<main::>, like C<STDOUT>, C<ARGV>, C<ENV>, and the punctuation variables. A package statement affects dynamic variables only, including those you've used C<local> on, but I<not> lexical variables, which are created with C<my>, C<state>, or C<our>. Typically it would be the first declaration in a file included by C<require> or C<use>. You can switch into a package in more than one place, since this only determines which default symbol table the compiler uses for the rest of that block. You can refer to identifiers in other packages than the current one by prefixing the identifier with the package name and a double colon, as in C<$SomePack::var> or C<ThatPack::INPUT_HANDLE>. If package name is omitted, the C<main> package as assumed. That is, C<$::sail> is equivalent to C<$main::sail> (as well as to C<$main'sail>, still seen in ancient code, mostly from Perl 4). If VERSION is provided, C<package> sets the C<$VERSION> variable in the given namespace to a L<version> object with the VERSION provided. VERSION must be a "strict" style version number as defined by the L<version> module: a positive decimal number (integer or decimal-fraction) without exponentiation or else a dotted-decimal v-string with a leading 'v' character and at least three components. You should set C<$VERSION> only once per package. See L<perlmod/"Packages"> for more information about packages, modules, and classes. See L<perlsub> for other scoping issues. =item __PACKAGE__ X<__PACKAGE__> =for Pod::Functions +5.004 the current package A special token that returns the name of the package in which it occurs. =item pipe READHANDLE,WRITEHANDLE X<pipe> =for Pod::Functions open a pair of connected filehandles Opens a pair of connected pipes like the corresponding system call. Note that if you set up a loop of piped processes, deadlock can occur unless you are very careful. In addition, note that Perl's pipes use IO buffering, so you may need to set C<$|> to flush your WRITEHANDLE after each command, depending on the application. See L<IPC::Open2>, L<IPC::Open3>, and L<perlipc/"Bidirectional Communication with Another Process"> for examples of such things. On systems that support a close-on-exec flag on files, that flag is set on all newly opened file descriptors whose C<fileno>s are I<higher> than the current value of $^F (by default 2 for C<STDERR>). See L<perlvar/$^F>. =item pop ARRAY X<pop> X<stack> =item pop EXPR =item pop =for Pod::Functions remove the last element from an array and return it Pops and returns the last value of the array, shortening the array by one element. Returns the undefined value if the array is empty, although this may also happen at other times. If ARRAY is omitted, pops the C<@ARGV> array in the main program, but the C<@_> array in subroutines, just like C<shift>. Starting with Perl 5.14, C<pop> can take a scalar EXPR, which must hold a reference to an unblessed array. The argument will be dereferenced automatically. This aspect of C<pop> is considered highly experimental. The exact behaviour may change in a future version of Perl. To avoid confusing would-be users of your code who are running earlier versions of Perl with mysterious syntax errors, put this sort of thing at the top of your file to signal that your code will work I<only> on Perls of a recent vintage: use 5.014; # so push/pop/etc work on scalars (experimental) =item pos SCALAR X<pos> X<match, position> =item pos =for Pod::Functions find or set the offset for the last/next m//g search Returns the offset of where the last C<m//g> search left off for the variable in question (C<$_> is used when the variable is not specified). Note that 0 is a valid match offset. C<undef> indicates that the search position is reset (usually due to match failure, but can also be because no match has yet been run on the scalar). C<pos> directly accesses the location used by the regexp engine to store the offset, so assigning to C<pos> will change that offset, and so will also influence the C<\G> zero-width assertion in regular expressions. Both of these effects take place for the next match, so you can't affect the position with C<pos> during the current match, such as in C<(?{pos() = 5})> or C<s//pos() = 5/e>. Setting C<pos> also resets the I<matched with zero-length> flag, described under L<perlre/"Repeated Patterns Matching a Zero-length Substring">. Because a failed C<m//gc> match doesn't reset the offset, the return from C<pos> won't change either in this case. See L<perlre> and L<perlop>. =item print FILEHANDLE LIST X<print> =item print FILEHANDLE =item print LIST =item print =for Pod::Functions output a list to a filehandle Prints a string or a list of strings. Returns true if successful. FILEHANDLE may be a scalar variable containing the name of or a reference to the filehandle, thus introducing one level of indirection. (NOTE: If FILEHANDLE is a variable and the next token is a term, it may be misinterpreted as an operator unless you interpose a C<+> or put parentheses around the arguments.) If FILEHANDLE is omitted, prints to the last selected (see L</select>) output handle. If LIST is omitted, prints C<$_> to the currently selected output handle. To use FILEHANDLE alone to print the content of C<$_> to it, you must use a real filehandle like C<FH>, not an indirect one like C<$fh>. To set the default output handle to something other than STDOUT, use the select operation. The current value of C<$,> (if any) is printed between each LIST item. The current value of C<$\> (if any) is printed after the entire LIST has been printed. Because print takes a LIST, anything in the LIST is evaluated in list context, including any subroutines whose return lists you pass to C<print>. Be careful not to follow the print keyword with a left parenthesis unless you want the corresponding right parenthesis to terminate the arguments to the print; put parentheses around all arguments (or interpose a C<+>, but that doesn't look as good). If you're storing handles in an array or hash, or in general whenever you're using any expression more complex than a bareword handle or a plain, unsubscripted scalar variable to retrieve it, you will have to use a block returning the filehandle value instead, in which case the LIST may not be omitted: print { $files[$i] } "stuff\n"; print { $OK ? STDOUT : STDERR } "stuff\n"; Printing to a closed pipe or socket will generate a SIGPIPE signal. See L<perlipc> for more on signal handling. =item printf FILEHANDLE FORMAT, LIST X<printf> =item printf FILEHANDLE =item printf FORMAT, LIST =item printf =for Pod::Functions output a formatted list to a filehandle Equivalent to C<print FILEHANDLE sprintf(FORMAT, LIST)>, except that C<$\> (the output record separator) is not appended. The first argument of the list will be interpreted as the C<printf> format. See L<sprintf|/sprintf FORMAT, LIST> for an explanation of the format argument. If you omit the LIST, C<$_> is used; to use FILEHANDLE without a LIST, you must use a real filehandle like C<FH>, not an indirect one like C<$fh>. If C<use locale> (including C<use locale ':not_characters'>) is in effect and POSIX::setlocale() has been called, the character used for the decimal separator in formatted floating-point numbers is affected by the LC_NUMERIC locale setting. See L<perllocale> and L<POSIX>. Don't fall into the trap of using a C<printf> when a simple C<print> would do. The C<print> is more efficient and less error prone. =item prototype FUNCTION X<prototype> =for Pod::Functions +5.002 get the prototype (if any) of a subroutine Returns the prototype of a function as a string (or C<undef> if the function has no prototype). FUNCTION is a reference to, or the name of, the function whose prototype you want to retrieve. If FUNCTION is a string starting with C<CORE::>, the rest is taken as a name for a Perl builtin. If the builtin is not I<overridable> (such as C<qw//>) or if its arguments cannot be adequately expressed by a prototype (such as C<system>), prototype() returns C<undef>, because the builtin does not really behave like a Perl function. Otherwise, the string describing the equivalent prototype is returned. =item push ARRAY,LIST X<push> X<stack> =item push EXPR,LIST =for Pod::Functions append one or more elements to an array Treats ARRAY as a stack by appending the values of LIST to the end of ARRAY. The length of ARRAY increases by the length of LIST. Has the same effect as for $value (LIST) { $ARRAY[++$#ARRAY] = $value; } but is more efficient. Returns the number of elements in the array following the completed C<push>. Starting with Perl 5.14, C<push> can take a scalar EXPR, which must hold a reference to an unblessed array. The argument will be dereferenced automatically. This aspect of C<push> is considered highly experimental. The exact behaviour may change in a future version of Perl. To avoid confusing would-be users of your code who are running earlier versions of Perl with mysterious syntax errors, put this sort of thing at the top of your file to signal that your code will work I<only> on Perls of a recent vintage: use 5.014; # so push/pop/etc work on scalars (experimental) =item q/STRING/ =for Pod::Functions singly quote a string =item qq/STRING/ =for Pod::Functions doubly quote a string =item qw/STRING/ =for Pod::Functions quote a list of words =item qx/STRING/ =for Pod::Functions backquote quote a string Generalized quotes. See L<perlop/"Quote-Like Operators">. =item qr/STRING/ =for Pod::Functions +5.005 compile pattern Regexp-like quote. See L<perlop/"Regexp Quote-Like Operators">. =item quotemeta EXPR X<quotemeta> X<metacharacter> =item quotemeta =for Pod::Functions quote regular expression magic characters Returns the value of EXPR with all the ASCII non-"word" characters backslashed. (That is, all ASCII characters not matching C</[A-Za-z_0-9]/> will be preceded by a backslash in the returned string, regardless of any locale settings.) This is the internal function implementing the C<\Q> escape in double-quoted strings. (See below for the behavior on non-ASCII code points.) If EXPR is omitted, uses C<$_>. quotemeta (and C<\Q> ... C<\E>) are useful when interpolating strings into regular expressions, because by default an interpolated variable will be considered a mini-regular expression. For example: my $sentence = 'The quick brown fox jumped over the lazy dog'; my $substring = 'quick.*?fox'; $sentence =~ s{$substring}{big bad wolf}; Will cause C<$sentence> to become C<'The big bad wolf jumped over...'>. On the other hand: my $sentence = 'The quick brown fox jumped over the lazy dog'; my $substring = 'quick.*?fox'; $sentence =~ s{\Q$substring\E}{big bad wolf}; Or: my $sentence = 'The quick brown fox jumped over the lazy dog'; my $substring = 'quick.*?fox'; my $quoted_substring = quotemeta($substring); $sentence =~ s{$quoted_substring}{big bad wolf}; Will both leave the sentence as is. Normally, when accepting literal string input from the user, quotemeta() or C<\Q> must be used. In Perl v5.14, all non-ASCII characters are quoted in non-UTF-8-encoded strings, but not quoted in UTF-8 strings. Starting in Perl v5.16, Perl adopted a Unicode-defined strategy for quoting non-ASCII characters; the quoting of ASCII characters is unchanged. Also unchanged is the quoting of non-UTF-8 strings when outside the scope of a C<use feature 'unicode_strings'>, which is to quote all characters in the upper Latin1 range. This provides complete backwards compatibility for old programs which do not use Unicode. (Note that C<unicode_strings> is automatically enabled within the scope of a S<C<use v5.12>> or greater.) Within the scope of C<use locale>, all non-ASCII Latin1 code points are quoted whether the string is encoded as UTF-8 or not. As mentioned above, locale does not affect the quoting of ASCII-range characters. This protects against those locales where characters such as C<"|"> are considered to be word characters. Otherwise, Perl quotes non-ASCII characters using an adaptation from Unicode (see L<http://www.unicode.org/reports/tr31/>.) The only code points that are quoted are those that have any of the Unicode properties: Pattern_Syntax, Pattern_White_Space, White_Space, Default_Ignorable_Code_Point, or General_Category=Control. Of these properties, the two important ones are Pattern_Syntax and Pattern_White_Space. They have been set up by Unicode for exactly this purpose of deciding which characters in a regular expression pattern should be quoted. No character that can be in an identifier has these properties. Perl promises, that if we ever add regular expression pattern metacharacters to the dozen already defined (C<\ E<verbar> ( ) [ { ^ $ * + ? .>), that we will only use ones that have the Pattern_Syntax property. Perl also promises, that if we ever add characters that are considered to be white space in regular expressions (currently mostly affected by C</x>), they will all have the Pattern_White_Space property. Unicode promises that the set of code points that have these two properties will never change, so something that is not quoted in v5.16 will never need to be quoted in any future Perl release. (Not all the code points that match Pattern_Syntax have actually had characters assigned to them; so there is room to grow, but they are quoted whether assigned or not. Perl, of course, would never use an unassigned code point as an actual metacharacter.) Quoting characters that have the other 3 properties is done to enhance the readability of the regular expression and not because they actually need to be quoted for regular expression purposes (characters with the White_Space property are likely to be indistinguishable on the page or screen from those with the Pattern_White_Space property; and the other two properties contain non-printing characters). =item rand EXPR X<rand> X<random> =item rand =for Pod::Functions retrieve the next pseudorandom number Returns a random fractional number greater than or equal to C<0> and less than the value of EXPR. (EXPR should be positive.) If EXPR is omitted, the value C<1> is used. Currently EXPR with the value C<0> is also special-cased as C<1> (this was undocumented before Perl 5.8.0 and is subject to change in future versions of Perl). Automatically calls C<srand> unless C<srand> has already been called. See also C<srand>. Apply C<int()> to the value returned by C<rand()> if you want random integers instead of random fractional numbers. For example, int(rand(10)) returns a random integer between C<0> and C<9>, inclusive. (Note: If your rand function consistently returns numbers that are too large or too small, then your version of Perl was probably compiled with the wrong number of RANDBITS.) B<C<rand()> is not cryptographically secure. You should not rely on it in security-sensitive situations.> As of this writing, a number of third-party CPAN modules offer random number generators intended by their authors to be cryptographically secure, including: L<Data::Entropy>, L<Crypt::Random>, L<Math::Random::Secure>, and L<Math::TrulyRandom>. =item read FILEHANDLE,SCALAR,LENGTH,OFFSET X<read> X<file, read> =item read FILEHANDLE,SCALAR,LENGTH =for Pod::Functions fixed-length buffered input from a filehandle Attempts to read LENGTH I<characters> of data into variable SCALAR from the specified FILEHANDLE. Returns the number of characters actually read, C<0> at end of file, or undef if there was an error (in the latter case C<$!> is also set). SCALAR will be grown or shrunk so that the last character actually read is the last character of the scalar after the read. An OFFSET may be specified to place the read data at some place in the string other than the beginning. A negative OFFSET specifies placement at that many characters counting backwards from the end of the string. A positive OFFSET greater than the length of SCALAR results in the string being padded to the required size with C<"\0"> bytes before the result of the read is appended. The call is implemented in terms of either Perl's or your system's native fread(3) library function. To get a true read(2) system call, see L<sysread|/sysread FILEHANDLE,SCALAR,LENGTH,OFFSET>. Note the I<characters>: depending on the status of the filehandle, either (8-bit) bytes or characters are read. By default, all filehandles operate on bytes, but for example if the filehandle has been opened with the C<:utf8> I/O layer (see L</open>, and the C<open> pragma, L<open>), the I/O will operate on UTF8-encoded Unicode characters, not bytes. Similarly for the C<:encoding> pragma: in that case pretty much any characters can be read. =item readdir DIRHANDLE X<readdir> =for Pod::Functions get a directory from a directory handle Returns the next directory entry for a directory opened by C<opendir>. If used in list context, returns all the rest of the entries in the directory. If there are no more entries, returns the undefined value in scalar context and the empty list in list context. If you're planning to filetest the return values out of a C<readdir>, you'd better prepend the directory in question. Otherwise, because we didn't C<chdir> there, it would have been testing the wrong file. opendir(my $dh, $some_dir) || die "can't opendir $some_dir: $!"; @dots = grep { /^\./ && -f "$some_dir/$_" } readdir($dh); closedir $dh; As of Perl 5.11.2 you can use a bare C<readdir> in a C<while> loop, which will set C<$_> on every iteration. opendir(my $dh, $some_dir) || die; while(readdir $dh) { print "$some_dir/$_\n"; } closedir $dh; To avoid confusing would-be users of your code who are running earlier versions of Perl with mysterious failures, put this sort of thing at the top of your file to signal that your code will work I<only> on Perls of a recent vintage: use 5.012; # so readdir assigns to $_ in a lone while test =item readline EXPR =item readline X<readline> X<gets> X<fgets> =for Pod::Functions fetch a record from a file Reads from the filehandle whose typeglob is contained in EXPR (or from C<*ARGV> if EXPR is not provided). In scalar context, each call reads and returns the next line until end-of-file is reached, whereupon the subsequent call returns C<undef>. In list context, reads until end-of-file is reached and returns a list of lines. Note that the notion of "line" used here is whatever you may have defined with C<$/> or C<$INPUT_RECORD_SEPARATOR>). See L<perlvar/"$/">. When C<$/> is set to C<undef>, when C<readline> is in scalar context (i.e., file slurp mode), and when an empty file is read, it returns C<''> the first time, followed by C<undef> subsequently. This is the internal function implementing the C<< <EXPR> >> operator, but you can use it directly. The C<< <EXPR> >> operator is discussed in more detail in L<perlop/"I/O Operators">. $line = <STDIN>; $line = readline(*STDIN); # same thing If C<readline> encounters an operating system error, C<$!> will be set with the corresponding error message. It can be helpful to check C<$!> when you are reading from filehandles you don't trust, such as a tty or a socket. The following example uses the operator form of C<readline> and dies if the result is not defined. while ( ! eof($fh) ) { defined( $_ = <$fh> ) or die "readline failed: $!"; ... } Note that you have can't handle C<readline> errors that way with the C<ARGV> filehandle. In that case, you have to open each element of C<@ARGV> yourself since C<eof> handles C<ARGV> differently. foreach my $arg (@ARGV) { open(my $fh, $arg) or warn "Can't open $arg: $!"; while ( ! eof($fh) ) { defined( $_ = <$fh> ) or die "readline failed for $arg: $!"; ... } } =item readlink EXPR X<readlink> =item readlink =for Pod::Functions determine where a symbolic link is pointing Returns the value of a symbolic link, if symbolic links are implemented. If not, raises an exception. If there is a system error, returns the undefined value and sets C<$!> (errno). If EXPR is omitted, uses C<$_>. Portability issues: L<perlport/readlink>. =item readpipe EXPR =item readpipe X<readpipe> =for Pod::Functions execute a system command and collect standard output EXPR is executed as a system command. The collected standard output of the command is returned. In scalar context, it comes back as a single (potentially multi-line) string. In list context, returns a list of lines (however you've defined lines with C<$/> or C<$INPUT_RECORD_SEPARATOR>). This is the internal function implementing the C<qx/EXPR/> operator, but you can use it directly. The C<qx/EXPR/> operator is discussed in more detail in L<perlop/"I/O Operators">. If EXPR is omitted, uses C<$_>. =item recv SOCKET,SCALAR,LENGTH,FLAGS X<recv> =for Pod::Functions receive a message over a Socket Receives a message on a socket. Attempts to receive LENGTH characters of data into variable SCALAR from the specified SOCKET filehandle. SCALAR will be grown or shrunk to the length actually read. Takes the same flags as the system call of the same name. Returns the address of the sender if SOCKET's protocol supports this; returns an empty string otherwise. If there's an error, returns the undefined value. This call is actually implemented in terms of recvfrom(2) system call. See L<perlipc/"UDP: Message Passing"> for examples. Note the I<characters>: depending on the status of the socket, either (8-bit) bytes or characters are received. By default all sockets operate on bytes, but for example if the socket has been changed using binmode() to operate with the C<:encoding(utf8)> I/O layer (see the C<open> pragma, L<open>), the I/O will operate on UTF8-encoded Unicode characters, not bytes. Similarly for the C<:encoding> pragma: in that case pretty much any characters can be read. =item redo LABEL X<redo> =item redo =for Pod::Functions start this loop iteration over again The C<redo> command restarts the loop block without evaluating the conditional again. The C<continue> block, if any, is not executed. If the LABEL is omitted, the command refers to the innermost enclosing loop. Programs that want to lie to themselves about what was just input normally use this command: # a simpleminded Pascal comment stripper # (warning: assumes no { or } in strings) LINE: while (<STDIN>) { while (s|({.*}.*){.*}|$1 |) {} s|{.*}| |; if (s|{.*| |) { $front = $_; while (<STDIN>) { if (/}/) { # end of comment? s|^|$front\{|; redo LINE; } } } print; } C<redo> cannot be used to retry a block that returns a value such as C<eval {}>, C<sub {}>, or C<do {}>, and should not be used to exit a grep() or map() operation. Note that a block by itself is semantically identical to a loop that executes once. Thus C<redo> inside such a block will effectively turn it into a looping construct. See also L</continue> for an illustration of how C<last>, C<next>, and C<redo> work. =item ref EXPR X<ref> X<reference> =item ref =for Pod::Functions find out the type of thing being referenced Returns a non-empty string if EXPR is a reference, the empty string otherwise. If EXPR is not specified, C<$_> will be used. The value returned depends on the type of thing the reference is a reference to. Builtin types include: SCALAR ARRAY HASH CODE REF GLOB LVALUE FORMAT IO VSTRING Regexp If the referenced object has been blessed into a package, then that package name is returned instead. You can think of C<ref> as a C<typeof> operator. if (ref($r) eq "HASH") { print "r is a reference to a hash.\n"; } unless (ref($r)) { print "r is not a reference at all.\n"; } The return value C<LVALUE> indicates a reference to an lvalue that is not a variable. You get this from taking the reference of function calls like C<pos()> or C<substr()>. C<VSTRING> is returned if the reference points to a L<version string|perldata/"Version Strings">. The result C<Regexp> indicates that the argument is a regular expression resulting from C<qr//>. See also L<perlref>. =item rename OLDNAME,NEWNAME X<rename> X<move> X<mv> X<ren> =for Pod::Functions change a filename Changes the name of a file; an existing file NEWNAME will be clobbered. Returns true for success, false otherwise. Behavior of this function varies wildly depending on your system implementation. For example, it will usually not work across file system boundaries, even though the system I<mv> command sometimes compensates for this. Other restrictions include whether it works on directories, open files, or pre-existing files. Check L<perlport> and either the rename(2) manpage or equivalent system documentation for details. For a platform independent C<move> function look at the L<File::Copy> module. Portability issues: L<perlport/rename>. =item require VERSION X<require> =item require EXPR =item require =for Pod::Functions load in external functions from a library at runtime Demands a version of Perl specified by VERSION, or demands some semantics specified by EXPR or by C<$_> if EXPR is not supplied. VERSION may be either a numeric argument such as 5.006, which will be compared to C<$]>, or a literal of the form v5.6.1, which will be compared to C<$^V> (aka $PERL_VERSION). An exception is raised if VERSION is greater than the version of the current Perl interpreter. Compare with L</use>, which can do a similar check at compile time. Specifying VERSION as a literal of the form v5.6.1 should generally be avoided, because it leads to misleading error messages under earlier versions of Perl that do not support this syntax. The equivalent numeric version should be used instead. require v5.6.1; # run time version check require 5.6.1; # ditto require 5.006_001; # ditto; preferred for backwards compatibility Otherwise, C<require> demands that a library file be included if it hasn't already been included. The file is included via the do-FILE mechanism, which is essentially just a variety of C<eval> with the caveat that lexical variables in the invoking script will be invisible to the included code. Has semantics similar to the following subroutine: sub require { my ($filename) = @_; if (exists $INC{$filename}) { return 1 if $INC{$filename}; die "Compilation failed in require"; } my ($realfilename,$result); ITER: { foreach $prefix (@INC) { $realfilename = "$prefix/$filename"; if (-f $realfilename) { $INC{$filename} = $realfilename; $result = do $realfilename; last ITER; } } die "Can't find $filename in \@INC"; } if ($@) { $INC{$filename} = undef; die $@; } elsif (!$result) { delete $INC{$filename}; die "$filename did not return true value"; } else { return $result; } } Note that the file will not be included twice under the same specified name. The file must return true as the last statement to indicate successful execution of any initialization code, so it's customary to end such a file with C<1;> unless you're sure it'll return true otherwise. But it's better just to put the C<1;>, in case you add more statements. If EXPR is a bareword, the require assumes a "F<.pm>" extension and replaces "F<::>" with "F</>" in the filename for you, to make it easy to load standard modules. This form of loading of modules does not risk altering your namespace. In other words, if you try this: require Foo::Bar; # a splendid bareword The require function will actually look for the "F<Foo/Bar.pm>" file in the directories specified in the C<@INC> array. But if you try this: $class = 'Foo::Bar'; require $class; # $class is not a bareword #or require "Foo::Bar"; # not a bareword because of the "" The require function will look for the "F<Foo::Bar>" file in the @INC array and will complain about not finding "F<Foo::Bar>" there. In this case you can do: eval "require $class"; Now that you understand how C<require> looks for files with a bareword argument, there is a little extra functionality going on behind the scenes. Before C<require> looks for a "F<.pm>" extension, it will first look for a similar filename with a "F<.pmc>" extension. If this file is found, it will be loaded in place of any file ending in a "F<.pm>" extension. You can also insert hooks into the import facility by putting Perl code directly into the @INC array. There are three forms of hooks: subroutine references, array references, and blessed objects. Subroutine references are the simplest case. When the inclusion system walks through @INC and encounters a subroutine, this subroutine gets called with two parameters, the first a reference to itself, and the second the name of the file to be included (e.g., "F<Foo/Bar.pm>"). The subroutine should return either nothing or else a list of up to three values in the following order: =over =item 1 A filehandle, from which the file will be read. =item 2 A reference to a subroutine. If there is no filehandle (previous item), then this subroutine is expected to generate one line of source code per call, writing the line into C<$_> and returning 1, then finally at end of file returning 0. If there is a filehandle, then the subroutine will be called to act as a simple source filter, with the line as read in C<$_>. Again, return 1 for each valid line, and 0 after all lines have been returned. =item 3 Optional state for the subroutine. The state is passed in as C<$_[1]>. A reference to the subroutine itself is passed in as C<$_[0]>. =back If an empty list, C<undef>, or nothing that matches the first 3 values above is returned, then C<require> looks at the remaining elements of @INC. Note that this filehandle must be a real filehandle (strictly a typeglob or reference to a typeglob, whether blessed or unblessed); tied filehandles will be ignored and processing will stop there. If the hook is an array reference, its first element must be a subroutine reference. This subroutine is called as above, but the first parameter is the array reference. This lets you indirectly pass arguments to the subroutine. In other words, you can write: push @INC, \&my_sub; sub my_sub { my ($coderef, $filename) = @_; # $coderef is \&my_sub ... } or: push @INC, [ \&my_sub, $x, $y, ... ]; sub my_sub { my ($arrayref, $filename) = @_; # Retrieve $x, $y, ... my @parameters = @$arrayref[1..$#$arrayref]; ... } If the hook is an object, it must provide an INC method that will be called as above, the first parameter being the object itself. (Note that you must fully qualify the sub's name, as unqualified C<INC> is always forced into package C<main>.) Here is a typical code layout: # In Foo.pm package Foo; sub new { ... } sub Foo::INC { my ($self, $filename) = @_; ... } # In the main program push @INC, Foo->new(...); These hooks are also permitted to set the %INC entry corresponding to the files they have loaded. See L<perlvar/%INC>. For a yet-more-powerful import facility, see L</use> and L<perlmod>. =item reset EXPR X<reset> =item reset =for Pod::Functions clear all variables of a given name Generally used in a C<continue> block at the end of a loop to clear variables and reset C<??> searches so that they work again. The expression is interpreted as a list of single characters (hyphens allowed for ranges). All variables and arrays beginning with one of those letters are reset to their pristine state. If the expression is omitted, one-match searches (C<?pattern?>) are reset to match again. Only resets variables or searches in the current package. Always returns 1. Examples: reset 'X'; # reset all X variables reset 'a-z'; # reset lower case variables reset; # just reset ?one-time? searches Resetting C<"A-Z"> is not recommended because you'll wipe out your C<@ARGV> and C<@INC> arrays and your C<%ENV> hash. Resets only package variables; lexical variables are unaffected, but they clean themselves up on scope exit anyway, so you'll probably want to use them instead. See L</my>. =item return EXPR X<return> =item return =for Pod::Functions get out of a function early Returns from a subroutine, C<eval>, or C<do FILE> with the value given in EXPR. Evaluation of EXPR may be in list, scalar, or void context, depending on how the return value will be used, and the context may vary from one execution to the next (see L</wantarray>). If no EXPR is given, returns an empty list in list context, the undefined value in scalar context, and (of course) nothing at all in void context. (In the absence of an explicit C<return>, a subroutine, eval, or do FILE automatically returns the value of the last expression evaluated.) =item reverse LIST X<reverse> X<rev> X<invert> =for Pod::Functions flip a string or a list In list context, returns a list value consisting of the elements of LIST in the opposite order. In scalar context, concatenates the elements of LIST and returns a string value with all characters in the opposite order. print join(", ", reverse "world", "Hello"); # Hello, world print scalar reverse "dlrow ,", "olleH"; # Hello, world Used without arguments in scalar context, reverse() reverses C<$_>. $_ = "dlrow ,olleH"; print reverse; # No output, list context print scalar reverse; # Hello, world Note that reversing an array to itself (as in C<@a = reverse @a>) will preserve non-existent elements whenever possible, i.e., for non magical arrays or tied arrays with C<EXISTS> and C<DELETE> methods. This operator is also handy for inverting a hash, although there are some caveats. If a value is duplicated in the original hash, only one of those can be represented as a key in the inverted hash. Also, this has to unwind one hash and build a whole new one, which may take some time on a large hash, such as from a DBM file. %by_name = reverse %by_address; # Invert the hash =item rewinddir DIRHANDLE X<rewinddir> =for Pod::Functions reset directory handle Sets the current position to the beginning of the directory for the C<readdir> routine on DIRHANDLE. Portability issues: L<perlport/rewinddir>. =item rindex STR,SUBSTR,POSITION X<rindex> =item rindex STR,SUBSTR =for Pod::Functions right-to-left substring search Works just like index() except that it returns the position of the I<last> occurrence of SUBSTR in STR. If POSITION is specified, returns the last occurrence beginning at or before that position. =item rmdir FILENAME X<rmdir> X<rd> X<directory, remove> =item rmdir =for Pod::Functions remove a directory Deletes the directory specified by FILENAME if that directory is empty. If it succeeds it returns true; otherwise it returns false and sets C<$!> (errno). If FILENAME is omitted, uses C<$_>. To remove a directory tree recursively (C<rm -rf> on Unix) look at the C<rmtree> function of the L<File::Path> module. =item s/// =for Pod::Functions replace a pattern with a string The substitution operator. See L<perlop/"Regexp Quote-Like Operators">. =item say FILEHANDLE LIST X<say> =item say FILEHANDLE =item say LIST =item say =for Pod::Functions +say output a list to a filehandle, appending a newline Just like C<print>, but implicitly appends a newline. C<say LIST> is simply an abbreviation for C<{ local $\ = "\n"; print LIST }>. To use FILEHANDLE without a LIST to print the contents of C<$_> to it, you must use a real filehandle like C<FH>, not an indirect one like C<$fh>. This keyword is available only when the C<"say"> feature is enabled, or when prefixed with C<CORE::>; see L<feature>. Alternately, include a C<use v5.10> or later to the current scope. =item scalar EXPR X<scalar> X<context> =for Pod::Functions force a scalar context Forces EXPR to be interpreted in scalar context and returns the value of EXPR. @counts = ( scalar @a, scalar @b, scalar @c ); There is no equivalent operator to force an expression to be interpolated in list context because in practice, this is never needed. If you really wanted to do so, however, you could use the construction C<@{[ (some expression) ]}>, but usually a simple C<(some expression)> suffices. Because C<scalar> is a unary operator, if you accidentally use a parenthesized list for the EXPR, this behaves as a scalar comma expression, evaluating all but the last element in void context and returning the final element evaluated in scalar context. This is seldom what you want. The following single statement: print uc(scalar(&foo,$bar)),$baz; is the moral equivalent of these two: &foo; print(uc($bar),$baz); See L<perlop> for more details on unary operators and the comma operator. =item seek FILEHANDLE,POSITION,WHENCE X<seek> X<fseek> X<filehandle, position> =for Pod::Functions reposition file pointer for random-access I/O Sets FILEHANDLE's position, just like the C<fseek> call of C<stdio>. FILEHANDLE may be an expression whose value gives the name of the filehandle. The values for WHENCE are C<0> to set the new position I<in bytes> to POSITION; C<1> to set it to the current position plus POSITION; and C<2> to set it to EOF plus POSITION, typically negative. For WHENCE you may use the constants C<SEEK_SET>, C<SEEK_CUR>, and C<SEEK_END> (start of the file, current position, end of the file) from the L<Fcntl> module. Returns C<1> on success, false otherwise. Note the I<in bytes>: even if the filehandle has been set to operate on characters (for example by using the C<:encoding(utf8)> open layer), tell() will return byte offsets, not character offsets (because implementing that would render seek() and tell() rather slow). If you want to position the file for C<sysread> or C<syswrite>, don't use C<seek>, because buffering makes its effect on the file's read-write position unpredictable and non-portable. Use C<sysseek> instead. Due to the rules and rigors of ANSI C, on some systems you have to do a seek whenever you switch between reading and writing. Amongst other things, this may have the effect of calling stdio's clearerr(3). A WHENCE of C<1> (C<SEEK_CUR>) is useful for not moving the file position: seek(TEST,0,1); This is also useful for applications emulating C<tail -f>. Once you hit EOF on your read and then sleep for a while, you (probably) have to stick in a dummy seek() to reset things. The C<seek> doesn't change the position, but it I<does> clear the end-of-file condition on the handle, so that the next C<< <FILE> >> makes Perl try again to read something. (We hope.) If that doesn't work (some I/O implementations are particularly cantankerous), you might need something like this: for (;;) { for ($curpos = tell(FILE); $_ = <FILE>; $curpos = tell(FILE)) { # search for some stuff and put it into files } sleep($for_a_while); seek(FILE, $curpos, 0); } =item seekdir DIRHANDLE,POS X<seekdir> =for Pod::Functions reposition directory pointer Sets the current position for the C<readdir> routine on DIRHANDLE. POS must be a value returned by C<telldir>. C<seekdir> also has the same caveats about possible directory compaction as the corresponding system library routine. =item select FILEHANDLE X<select> X<filehandle, default> =item select =for Pod::Functions reset default output or do I/O multiplexing Returns the currently selected filehandle. If FILEHANDLE is supplied, sets the new current default filehandle for output. This has two effects: first, a C<write> or a C<print> without a filehandle default to this FILEHANDLE. Second, references to variables related to output will refer to this output channel. For example, to set the top-of-form format for more than one output channel, you might do the following: select(REPORT1); $^ = 'report1_top'; select(REPORT2); $^ = 'report2_top'; FILEHANDLE may be an expression whose value gives the name of the actual filehandle. Thus: $oldfh = select(STDERR); $| = 1; select($oldfh); Some programmers may prefer to think of filehandles as objects with methods, preferring to write the last example as: use IO::Handle; STDERR->autoflush(1); Portability issues: L<perlport/select>. =item select RBITS,WBITS,EBITS,TIMEOUT X<select> This calls the select(2) syscall with the bit masks specified, which can be constructed using C<fileno> and C<vec>, along these lines: $rin = $win = $ein = ''; vec($rin, fileno(STDIN), 1) = 1; vec($win, fileno(STDOUT), 1) = 1; $ein = $rin | $win; If you want to select on many filehandles, you may wish to write a subroutine like this: sub fhbits { my @fhlist = @_; my $bits = ""; for my $fh (@fhlist) { vec($bits, fileno($fh), 1) = 1; } return $bits; } $rin = fhbits(*STDIN, *TTY, *MYSOCK); The usual idiom is: ($nfound,$timeleft) = select($rout=$rin, $wout=$win, $eout=$ein, $timeout); or to block until something becomes ready just do this $nfound = select($rout=$rin, $wout=$win, $eout=$ein, undef); Most systems do not bother to return anything useful in $timeleft, so calling select() in scalar context just returns $nfound. Any of the bit masks can also be undef. The timeout, if specified, is in seconds, which may be fractional. Note: not all implementations are capable of returning the $timeleft. If not, they always return $timeleft equal to the supplied $timeout. You can effect a sleep of 250 milliseconds this way: select(undef, undef, undef, 0.25); Note that whether C<select> gets restarted after signals (say, SIGALRM) is implementation-dependent. See also L<perlport> for notes on the portability of C<select>. On error, C<select> behaves just like select(2): it returns -1 and sets C<$!>. On some Unixes, select(2) may report a socket file descriptor as "ready for reading" even when no data is available, and thus any subsequent C<read> would block. This can be avoided if you always use O_NONBLOCK on the socket. See select(2) and fcntl(2) for further details. The standard C<IO::Select> module provides a user-friendlier interface to C<select>, mostly because it does all the bit-mask work for you. B<WARNING>: One should not attempt to mix buffered I/O (like C<read> or <FH>) with C<select>, except as permitted by POSIX, and even then only on POSIX systems. You have to use C<sysread> instead. Portability issues: L<perlport/select>. =item semctl ID,SEMNUM,CMD,ARG X<semctl> =for Pod::Functions SysV semaphore control operations Calls the System V IPC function semctl(2). You'll probably have to say use IPC::SysV; first to get the correct constant definitions. If CMD is IPC_STAT or GETALL, then ARG must be a variable that will hold the returned semid_ds structure or semaphore value array. Returns like C<ioctl>: the undefined value for error, "C<0 but true>" for zero, or the actual return value otherwise. The ARG must consist of a vector of native short integers, which may be created with C<pack("s!",(0)x$nsem)>. See also L<perlipc/"SysV IPC">, C<IPC::SysV>, C<IPC::Semaphore> documentation. Portability issues: L<perlport/semctl>. =item semget KEY,NSEMS,FLAGS X<semget> =for Pod::Functions get set of SysV semaphores Calls the System V IPC function semget(2). Returns the semaphore id, or the undefined value on error. See also L<perlipc/"SysV IPC">, C<IPC::SysV>, C<IPC::SysV::Semaphore> documentation. Portability issues: L<perlport/semget>. =item semop KEY,OPSTRING X<semop> =for Pod::Functions SysV semaphore operations Calls the System V IPC function semop(2) for semaphore operations such as signalling and waiting. OPSTRING must be a packed array of semop structures. Each semop structure can be generated with C<pack("s!3", $semnum, $semop, $semflag)>. The length of OPSTRING implies the number of semaphore operations. Returns true if successful, false on error. As an example, the following code waits on semaphore $semnum of semaphore id $semid: $semop = pack("s!3", $semnum, -1, 0); die "Semaphore trouble: $!\n" unless semop($semid, $semop); To signal the semaphore, replace C<-1> with C<1>. See also L<perlipc/"SysV IPC">, C<IPC::SysV>, and C<IPC::SysV::Semaphore> documentation. Portability issues: L<perlport/semop>. =item send SOCKET,MSG,FLAGS,TO X<send> =item send SOCKET,MSG,FLAGS =for Pod::Functions send a message over a socket Sends a message on a socket. Attempts to send the scalar MSG to the SOCKET filehandle. Takes the same flags as the system call of the same name. On unconnected sockets, you must specify a destination to I<send to>, in which case it does a sendto(2) syscall. Returns the number of characters sent, or the undefined value on error. The sendmsg(2) syscall is currently unimplemented. See L<perlipc/"UDP: Message Passing"> for examples. Note the I<characters>: depending on the status of the socket, either (8-bit) bytes or characters are sent. By default all sockets operate on bytes, but for example if the socket has been changed using binmode() to operate with the C<:encoding(utf8)> I/O layer (see L</open>, or the C<open> pragma, L<open>), the I/O will operate on UTF-8 encoded Unicode characters, not bytes. Similarly for the C<:encoding> pragma: in that case pretty much any characters can be sent. =item setpgrp PID,PGRP X<setpgrp> X<group> =for Pod::Functions set the process group of a process Sets the current process group for the specified PID, C<0> for the current process. Raises an exception when used on a machine that doesn't implement POSIX setpgid(2) or BSD setpgrp(2). If the arguments are omitted, it defaults to C<0,0>. Note that the BSD 4.2 version of C<setpgrp> does not accept any arguments, so only C<setpgrp(0,0)> is portable. See also C<POSIX::setsid()>. Portability issues: L<perlport/setpgrp>. =item setpriority WHICH,WHO,PRIORITY X<setpriority> X<priority> X<nice> X<renice> =for Pod::Functions set a process's nice value Sets the current priority for a process, a process group, or a user. (See setpriority(2).) Raises an exception when used on a machine that doesn't implement setpriority(2). Portability issues: L<perlport/setpriority>. =item setsockopt SOCKET,LEVEL,OPTNAME,OPTVAL X<setsockopt> =for Pod::Functions set some socket options Sets the socket option requested. Returns C<undef> on error. Use integer constants provided by the C<Socket> module for LEVEL and OPNAME. Values for LEVEL can also be obtained from getprotobyname. OPTVAL might either be a packed string or an integer. An integer OPTVAL is shorthand for pack("i", OPTVAL). An example disabling Nagle's algorithm on a socket: use Socket qw(IPPROTO_TCP TCP_NODELAY); setsockopt($socket, IPPROTO_TCP, TCP_NODELAY, 1); Portability issues: L<perlport/setsockopt>. =item shift ARRAY X<shift> =item shift EXPR =item shift =for Pod::Functions remove the first element of an array, and return it Shifts the first value of the array off and returns it, shortening the array by 1 and moving everything down. If there are no elements in the array, returns the undefined value. If ARRAY is omitted, shifts the C<@_> array within the lexical scope of subroutines and formats, and the C<@ARGV> array outside a subroutine and also within the lexical scopes established by the C<eval STRING>, C<BEGIN {}>, C<INIT {}>, C<CHECK {}>, C<UNITCHECK {}>, and C<END {}> constructs. Starting with Perl 5.14, C<shift> can take a scalar EXPR, which must hold a reference to an unblessed array. The argument will be dereferenced automatically. This aspect of C<shift> is considered highly experimental. The exact behaviour may change in a future version of Perl. To avoid confusing would-be users of your code who are running earlier versions of Perl with mysterious syntax errors, put this sort of thing at the top of your file to signal that your code will work I<only> on Perls of a recent vintage: use 5.014; # so push/pop/etc work on scalars (experimental) See also C<unshift>, C<push>, and C<pop>. C<shift> and C<unshift> do the same thing to the left end of an array that C<pop> and C<push> do to the right end. =item shmctl ID,CMD,ARG X<shmctl> =for Pod::Functions SysV shared memory operations Calls the System V IPC function shmctl. You'll probably have to say use IPC::SysV; first to get the correct constant definitions. If CMD is C<IPC_STAT>, then ARG must be a variable that will hold the returned C<shmid_ds> structure. Returns like ioctl: C<undef> for error; "C<0> but true" for zero; and the actual return value otherwise. See also L<perlipc/"SysV IPC"> and C<IPC::SysV> documentation. Portability issues: L<perlport/shmctl>. =item shmget KEY,SIZE,FLAGS X<shmget> =for Pod::Functions get SysV shared memory segment identifier Calls the System V IPC function shmget. Returns the shared memory segment id, or C<undef> on error. See also L<perlipc/"SysV IPC"> and C<IPC::SysV> documentation. Portability issues: L<perlport/shmget>. =item shmread ID,VAR,POS,SIZE X<shmread> X<shmwrite> =for Pod::Functions read SysV shared memory =item shmwrite ID,STRING,POS,SIZE =for Pod::Functions write SysV shared memory Reads or writes the System V shared memory segment ID starting at position POS for size SIZE by attaching to it, copying in/out, and detaching from it. When reading, VAR must be a variable that will hold the data read. When writing, if STRING is too long, only SIZE bytes are used; if STRING is too short, nulls are written to fill out SIZE bytes. Return true if successful, false on error. shmread() taints the variable. See also L<perlipc/"SysV IPC">, C<IPC::SysV>, and the C<IPC::Shareable> module from CPAN. Portability issues: L<perlport/shmread> and L<perlport/shmwrite>. =item shutdown SOCKET,HOW X<shutdown> =for Pod::Functions close down just half of a socket connection Shuts down a socket connection in the manner indicated by HOW, which has the same interpretation as in the syscall of the same name. shutdown(SOCKET, 0); # I/we have stopped reading data shutdown(SOCKET, 1); # I/we have stopped writing data shutdown(SOCKET, 2); # I/we have stopped using this socket This is useful with sockets when you want to tell the other side you're done writing but not done reading, or vice versa. It's also a more insistent form of close because it also disables the file descriptor in any forked copies in other processes. Returns C<1> for success; on error, returns C<undef> if the first argument is not a valid filehandle, or returns C<0> and sets C<$!> for any other failure. =item sin EXPR X<sin> X<sine> X<asin> X<arcsine> =item sin =for Pod::Functions return the sine of a number Returns the sine of EXPR (expressed in radians). If EXPR is omitted, returns sine of C<$_>. For the inverse sine operation, you may use the C<Math::Trig::asin> function, or use this relation: sub asin { atan2($_[0], sqrt(1 - $_[0] * $_[0])) } =item sleep EXPR X<sleep> X<pause> =item sleep =for Pod::Functions block for some number of seconds Causes the script to sleep for (integer) EXPR seconds, or forever if no argument is given. Returns the integer number of seconds actually slept. May be interrupted if the process receives a signal such as C<SIGALRM>. eval { local $SIG{ALARM} = sub { die "Alarm!\n" }; sleep; }; die $@ unless $@ eq "Alarm!\n"; You probably cannot mix C<alarm> and C<sleep> calls, because C<sleep> is often implemented using C<alarm>. On some older systems, it may sleep up to a full second less than what you requested, depending on how it counts seconds. Most modern systems always sleep the full amount. They may appear to sleep longer than that, however, because your process might not be scheduled right away in a busy multitasking system. For delays of finer granularity than one second, the Time::HiRes module (from CPAN, and starting from Perl 5.8 part of the standard distribution) provides usleep(). You may also use Perl's four-argument version of select() leaving the first three arguments undefined, or you might be able to use the C<syscall> interface to access setitimer(2) if your system supports it. See L<perlfaq8> for details. See also the POSIX module's C<pause> function. =item socket SOCKET,DOMAIN,TYPE,PROTOCOL X<socket> =for Pod::Functions create a socket Opens a socket of the specified kind and attaches it to filehandle SOCKET. DOMAIN, TYPE, and PROTOCOL are specified the same as for the syscall of the same name. You should C<use Socket> first to get the proper definitions imported. See the examples in L<perlipc/"Sockets: Client/Server Communication">. On systems that support a close-on-exec flag on files, the flag will be set for the newly opened file descriptor, as determined by the value of $^F. See L<perlvar/$^F>. =item socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL X<socketpair> =for Pod::Functions create a pair of sockets Creates an unnamed pair of sockets in the specified domain, of the specified type. DOMAIN, TYPE, and PROTOCOL are specified the same as for the syscall of the same name. If unimplemented, raises an exception. Returns true if successful. On systems that support a close-on-exec flag on files, the flag will be set for the newly opened file descriptors, as determined by the value of $^F. See L<perlvar/$^F>. Some systems defined C<pipe> in terms of C<socketpair>, in which a call to C<pipe(Rdr, Wtr)> is essentially: use Socket; socketpair(Rdr, Wtr, AF_UNIX, SOCK_STREAM, PF_UNSPEC); shutdown(Rdr, 1); # no more writing for reader shutdown(Wtr, 0); # no more reading for writer See L<perlipc> for an example of socketpair use. Perl 5.8 and later will emulate socketpair using IP sockets to localhost if your system implements sockets but not socketpair. Portability issues: L<perlport/socketpair>. =item sort SUBNAME LIST X<sort> X<qsort> X<quicksort> X<mergesort> =item sort BLOCK LIST =item sort LIST =for Pod::Functions sort a list of values In list context, this sorts the LIST and returns the sorted list value. In scalar context, the behaviour of C<sort()> is undefined. If SUBNAME or BLOCK is omitted, C<sort>s in standard string comparison order. If SUBNAME is specified, it gives the name of a subroutine that returns an integer less than, equal to, or greater than C<0>, depending on how the elements of the list are to be ordered. (The C<< <=> >> and C<cmp> operators are extremely useful in such routines.) SUBNAME may be a scalar variable name (unsubscripted), in which case the value provides the name of (or a reference to) the actual subroutine to use. In place of a SUBNAME, you can provide a BLOCK as an anonymous, in-line sort subroutine. If the subroutine's prototype is C<($$)>, the elements to be compared are passed by reference in C<@_>, as for a normal subroutine. This is slower than unprototyped subroutines, where the elements to be compared are passed into the subroutine as the package global variables $a and $b (see example below). Note that in the latter case, it is usually highly counter-productive to declare $a and $b as lexicals. If the subroutine is an XSUB, the elements to be compared are pushed on to the stack, the way arguments are usually passed to XSUBs. $a and $b are not set. The values to be compared are always passed by reference and should not be modified. You also cannot exit out of the sort block or subroutine using any of the loop control operators described in L<perlsyn> or with C<goto>. When C<use locale> (but not C<use locale 'not_characters'>) is in effect, C<sort LIST> sorts LIST according to the current collation locale. See L<perllocale>. sort() returns aliases into the original list, much as a for loop's index variable aliases the list elements. That is, modifying an element of a list returned by sort() (for example, in a C<foreach>, C<map> or C<grep>) actually modifies the element in the original list. This is usually something to be avoided when writing clear code. Perl 5.6 and earlier used a quicksort algorithm to implement sort. That algorithm was not stable, so I<could> go quadratic. (A I<stable> sort preserves the input order of elements that compare equal. Although quicksort's run time is O(NlogN) when averaged over all arrays of length N, the time can be O(N**2), I<quadratic> behavior, for some inputs.) In 5.7, the quicksort implementation was replaced with a stable mergesort algorithm whose worst-case behavior is O(NlogN). But benchmarks indicated that for some inputs, on some platforms, the original quicksort was faster. 5.8 has a sort pragma for limited control of the sort. Its rather blunt control of the underlying algorithm may not persist into future Perls, but the ability to characterize the input or output in implementation independent ways quite probably will. See L<the sort pragma|sort>. Examples: # sort lexically @articles = sort @files; # same thing, but with explicit sort routine @articles = sort {$a cmp $b} @files; # now case-insensitively @articles = sort {fc($a) cmp fc($b)} @files; # same thing in reversed order @articles = sort {$b cmp $a} @files; # sort numerically ascending @articles = sort {$a <=> $b} @files; # sort numerically descending @articles = sort {$b <=> $a} @files; # this sorts the %age hash by value instead of key # using an in-line function @eldest = sort { $age{$b} <=> $age{$a} } keys %age; # sort using explicit subroutine name sub byage { $age{$a} <=> $age{$b}; # presuming numeric } @sortedclass = sort byage @class; sub backwards { $b cmp $a } @harry = qw(dog cat x Cain Abel); @george = qw(gone chased yz Punished Axed); print sort @harry; # prints AbelCaincatdogx print sort backwards @harry; # prints xdogcatCainAbel print sort @george, 'to', @harry; # prints AbelAxedCainPunishedcatchaseddoggonetoxyz # inefficiently sort by descending numeric compare using # the first integer after the first = sign, or the # whole record case-insensitively otherwise my @new = sort { ($b =~ /=(\d+)/)[0] <=> ($a =~ /=(\d+)/)[0] || fc($a) cmp fc($b) } @old; # same thing, but much more efficiently; # we'll build auxiliary indices instead # for speed my @nums = @caps = (); for (@old) { push @nums, ( /=(\d+)/ ? $1 : undef ); push @caps, fc($_); } my @new = @old[ sort { $nums[$b] <=> $nums[$a] || $caps[$a] cmp $caps[$b] } 0..$#old ]; # same thing, but without any temps @new = map { $_->[0] } sort { $b->[1] <=> $a->[1] || $a->[2] cmp $b->[2] } map { [$_, /=(\d+)/, fc($_)] } @old; # using a prototype allows you to use any comparison subroutine # as a sort subroutine (including other package's subroutines) package other; sub backwards ($$) { $_[1] cmp $_[0]; } # $a and $b are not set here package main; @new = sort other::backwards @old; # guarantee stability, regardless of algorithm use sort 'stable'; @new = sort { substr($a, 3, 5) cmp substr($b, 3, 5) } @old; # force use of mergesort (not portable outside Perl 5.8) use sort '_mergesort'; # note discouraging _ @new = sort { substr($a, 3, 5) cmp substr($b, 3, 5) } @old; Warning: syntactical care is required when sorting the list returned from a function. If you want to sort the list returned by the function call C<find_records(@key)>, you can use: @contact = sort { $a cmp $b } find_records @key; @contact = sort +find_records(@key); @contact = sort &find_records(@key); @contact = sort(find_records(@key)); If instead you want to sort the array @key with the comparison routine C<find_records()> then you can use: @contact = sort { find_records() } @key; @contact = sort find_records(@key); @contact = sort(find_records @key); @contact = sort(find_records (@key)); If you're using strict, you I<must not> declare $a and $b as lexicals. They are package globals. That means that if you're in the C<main> package and type @articles = sort {$b <=> $a} @files; then C<$a> and C<$b> are C<$main::a> and C<$main::b> (or C<$::a> and C<$::b>), but if you're in the C<FooPack> package, it's the same as typing @articles = sort {$FooPack::b <=> $FooPack::a} @files; The comparison function is required to behave. If it returns inconsistent results (sometimes saying C<$x[1]> is less than C<$x[2]> and sometimes saying the opposite, for example) the results are not well-defined. Because C<< <=> >> returns C<undef> when either operand is C<NaN> (not-a-number), be careful when sorting with a comparison function like C<< $a <=> $b >> any lists that might contain a C<NaN>. The following example takes advantage that C<NaN != NaN> to eliminate any C<NaN>s from the input list. @result = sort { $a <=> $b } grep { $_ == $_ } @input; =item splice ARRAY or EXPR,OFFSET,LENGTH,LIST X<splice> =item splice ARRAY or EXPR,OFFSET,LENGTH =item splice ARRAY or EXPR,OFFSET =item splice ARRAY or EXPR =for Pod::Functions add or remove elements anywhere in an array Removes the elements designated by OFFSET and LENGTH from an array, and replaces them with the elements of LIST, if any. In list context, returns the elements removed from the array. In scalar context, returns the last element removed, or C<undef> if no elements are removed. The array grows or shrinks as necessary. If OFFSET is negative then it starts that far from the end of the array. If LENGTH is omitted, removes everything from OFFSET onward. If LENGTH is negative, removes the elements from OFFSET onward except for -LENGTH elements at the end of the array. If both OFFSET and LENGTH are omitted, removes everything. If OFFSET is past the end of the array, Perl issues a warning, and splices at the end of the array. The following equivalences hold (assuming C<< $#a >= $i >> ) push(@a,$x,$y) splice(@a,@a,0,$x,$y) pop(@a) splice(@a,-1) shift(@a) splice(@a,0,1) unshift(@a,$x,$y) splice(@a,0,0,$x,$y) $a[$i] = $y splice(@a,$i,1,$y) Example, assuming array lengths are passed before arrays: sub aeq { # compare two list values my(@a) = splice(@_,0,shift); my(@b) = splice(@_,0,shift); return 0 unless @a == @b; # same len? while (@a) { return 0 if pop(@a) ne pop(@b); } return 1; } if (&aeq($len,@foo[1..$len],0+@bar,@bar)) { ... } Starting with Perl 5.14, C<splice> can take scalar EXPR, which must hold a reference to an unblessed array. The argument will be dereferenced automatically. This aspect of C<splice> is considered highly experimental. The exact behaviour may change in a future version of Perl. To avoid confusing would-be users of your code who are running earlier versions of Perl with mysterious syntax errors, put this sort of thing at the top of your file to signal that your code will work I<only> on Perls of a recent vintage: use 5.014; # so push/pop/etc work on scalars (experimental) =item split /PATTERN/,EXPR,LIMIT X<split> =item split /PATTERN/,EXPR =item split /PATTERN/ =item split =for Pod::Functions split up a string using a regexp delimiter Splits the string EXPR into a list of strings and returns the list in list context, or the size of the list in scalar context. If only PATTERN is given, EXPR defaults to C<$_>. Anything in EXPR that matches PATTERN is taken to be a separator that separates the EXPR into substrings (called "I<fields>") that do B<not> include the separator. Note that a separator may be longer than one character or even have no characters at all (the empty string, which is a zero-width match). The PATTERN need not be constant; an expression may be used to specify a pattern that varies at runtime. If PATTERN matches the empty string, the EXPR is split at the match position (between characters). As an example, the following: print join(':', split('b', 'abc')), "\n"; uses the 'b' in 'abc' as a separator to produce the output 'a:c'. However, this: print join(':', split('', 'abc')), "\n"; uses empty string matches as separators to produce the output 'a:b:c'; thus, the empty string may be used to split EXPR into a list of its component characters. As a special case for C<split>, the empty pattern given in L<match operator|perlop/"m/PATTERN/msixpodualgc"> syntax (C<//>) specifically matches the empty string, which is contrary to its usual interpretation as the last successful match. If PATTERN is C</^/>, then it is treated as if it used the L<multiline modifier|perlreref/OPERATORS> (C</^/m>), since it isn't much use otherwise. As another special case, C<split> emulates the default behavior of the command line tool B<awk> when the PATTERN is either omitted or a I<literal string> composed of a single space character (such as S<C<' '>> or S<C<"\x20">>, but not e.g. S<C</ />>). In this case, any leading whitespace in EXPR is removed before splitting occurs, and the PATTERN is instead treated as if it were C</\s+/>; in particular, this means that I<any> contiguous whitespace (not just a single space character) is used as a separator. However, this special treatment can be avoided by specifying the pattern S<C</ />> instead of the string S<C<" ">>, thereby allowing only a single space character to be a separator. If omitted, PATTERN defaults to a single space, S<C<" ">>, triggering the previously described I<awk> emulation. If LIMIT is specified and positive, it represents the maximum number of fields into which the EXPR may be split; in other words, LIMIT is one greater than the maximum number of times EXPR may be split. Thus, the LIMIT value C<1> means that EXPR may be split a maximum of zero times, producing a maximum of one field (namely, the entire value of EXPR). For instance: print join(':', split(//, 'abc', 1)), "\n"; produces the output 'abc', and this: print join(':', split(//, 'abc', 2)), "\n"; produces the output 'a:bc', and each of these: print join(':', split(//, 'abc', 3)), "\n"; print join(':', split(//, 'abc', 4)), "\n"; produces the output 'a:b:c'. If LIMIT is negative, it is treated as if it were instead arbitrarily large; as many fields as possible are produced. If LIMIT is omitted (or, equivalently, zero), then it is usually treated as if it were instead negative but with the exception that trailing empty fields are stripped (empty leading fields are always preserved); if all fields are empty, then all fields are considered to be trailing (and are thus stripped in this case). Thus, the following: print join(':', split(',', 'a,b,c,,,')), "\n"; produces the output 'a:b:c', but the following: print join(':', split(',', 'a,b,c,,,', -1)), "\n"; produces the output 'a:b:c:::'. In time-critical applications, it is worthwhile to avoid splitting into more fields than necessary. Thus, when assigning to a list, if LIMIT is omitted (or zero), then LIMIT is treated as though it were one larger than the number of variables in the list; for the following, LIMIT is implicitly 4: ($login, $passwd, $remainder) = split(/:/); Note that splitting an EXPR that evaluates to the empty string always produces zero fields, regardless of the LIMIT specified. An empty leading field is produced when there is a positive-width match at the beginning of EXPR. For instance: print join(':', split(/ /, ' abc')), "\n"; produces the output ':abc'. However, a zero-width match at the beginning of EXPR never produces an empty field, so that: print join(':', split(//, ' abc')); produces the output S<' :a:b:c'> (rather than S<': :a:b:c'>). An empty trailing field, on the other hand, is produced when there is a match at the end of EXPR, regardless of the length of the match (of course, unless a non-zero LIMIT is given explicitly, such fields are removed, as in the last example). Thus: print join(':', split(//, ' abc', -1)), "\n"; produces the output S<' :a:b:c:'>. If the PATTERN contains L<capturing groups|perlretut/Grouping things and hierarchical matching>, then for each separator, an additional field is produced for each substring captured by a group (in the order in which the groups are specified, as per L<backreferences|perlretut/Backreferences>); if any group does not match, then it captures the C<undef> value instead of a substring. Also, note that any such additional field is produced whenever there is a separator (that is, whenever a split occurs), and such an additional field does B<not> count towards the LIMIT. Consider the following expressions evaluated in list context (each returned list is provided in the associated comment): split(/-|,/, "1-10,20", 3) # ('1', '10', '20') split(/(-|,)/, "1-10,20", 3) # ('1', '-', '10', ',', '20') split(/-|(,)/, "1-10,20", 3) # ('1', undef, '10', ',', '20') split(/(-)|,/, "1-10,20", 3) # ('1', '-', '10', undef, '20') split(/(-)|(,)/, "1-10,20", 3) # ('1', '-', undef, '10', undef, ',', '20') =item sprintf FORMAT, LIST X<sprintf> =for Pod::Functions formatted print into a string Returns a string formatted by the usual C<printf> conventions of the C library function C<sprintf>. See below for more details and see L<sprintf(3)> or L<printf(3)> on your system for an explanation of the general principles. For example: # Format number with up to 8 leading zeroes $result = sprintf("%08d", $number); # Round number to 3 digits after decimal point $rounded = sprintf("%.3f", $number); Perl does its own C<sprintf> formatting: it emulates the C function sprintf(3), but doesn't use it except for floating-point numbers, and even then only standard modifiers are allowed. Non-standard extensions in your local sprintf(3) are therefore unavailable from Perl. Unlike C<printf>, C<sprintf> does not do what you probably mean when you pass it an array as your first argument. The array is given scalar context, and instead of using the 0th element of the array as the format, Perl will use the count of elements in the array as the format, which is almost never useful. Perl's C<sprintf> permits the following universally-known conversions: %% a percent sign %c a character with the given number %s a string %d a signed integer, in decimal %u an unsigned integer, in decimal %o an unsigned integer, in octal %x an unsigned integer, in hexadecimal %e a floating-point number, in scientific notation %f a floating-point number, in fixed decimal notation %g a floating-point number, in %e or %f notation In addition, Perl permits the following widely-supported conversions: %X like %x, but using upper-case letters %E like %e, but using an upper-case "E" %G like %g, but with an upper-case "E" (if applicable) %b an unsigned integer, in binary %B like %b, but using an upper-case "B" with the # flag %p a pointer (outputs the Perl value's address in hexadecimal) %n special: *stores* the number of characters output so far into the next argument in the parameter list Finally, for backward (and we do mean "backward") compatibility, Perl permits these unnecessary but widely-supported conversions: %i a synonym for %d %D a synonym for %ld %U a synonym for %lu %O a synonym for %lo %F a synonym for %f Note that the number of exponent digits in the scientific notation produced by C<%e>, C<%E>, C<%g> and C<%G> for numbers with the modulus of the exponent less than 100 is system-dependent: it may be three or less (zero-padded as necessary). In other words, 1.23 times ten to the 99th may be either "1.23e99" or "1.23e099". Between the C<%> and the format letter, you may specify several additional attributes controlling the interpretation of the format. In order, these are: =over 4 =item format parameter index An explicit format parameter index, such as C<2$>. By default sprintf will format the next unused argument in the list, but this allows you to take the arguments out of order: printf '%2$d %1$d', 12, 34; # prints "34 12" printf '%3$d %d %1$d', 1, 2, 3; # prints "3 1 1" =item flags one or more of: space prefix non-negative number with a space + prefix non-negative number with a plus sign - left-justify within the field 0 use zeros, not spaces, to right-justify # ensure the leading "0" for any octal, prefix non-zero hexadecimal with "0x" or "0X", prefix non-zero binary with "0b" or "0B" For example: printf '<% d>', 12; # prints "< 12>" printf '<%+d>', 12; # prints "<+12>" printf '<%6s>', 12; # prints "< 12>" printf '<%-6s>', 12; # prints "<12 >" printf '<%06s>', 12; # prints "<000012>" printf '<%#o>', 12; # prints "<014>" printf '<%#x>', 12; # prints "<0xc>" printf '<%#X>', 12; # prints "<0XC>" printf '<%#b>', 12; # prints "<0b1100>" printf '<%#B>', 12; # prints "<0B1100>" When a space and a plus sign are given as the flags at once, a plus sign is used to prefix a positive number. printf '<%+ d>', 12; # prints "<+12>" printf '<% +d>', 12; # prints "<+12>" When the # flag and a precision are given in the %o conversion, the precision is incremented if it's necessary for the leading "0". printf '<%#.5o>', 012; # prints "<00012>" printf '<%#.5o>', 012345; # prints "<012345>" printf '<%#.0o>', 0; # prints "<0>" =item vector flag This flag tells Perl to interpret the supplied string as a vector of integers, one for each character in the string. Perl applies the format to each integer in turn, then joins the resulting strings with a separator (a dot C<.> by default). This can be useful for displaying ordinal values of characters in arbitrary strings: printf "%vd", "AB\x{100}"; # prints "65.66.256" printf "version is v%vd\n", $^V; # Perl's version Put an asterisk C<*> before the C<v> to override the string to use to separate the numbers: printf "address is %*vX\n", ":", $addr; # IPv6 address printf "bits are %0*v8b\n", " ", $bits; # random bitstring You can also explicitly specify the argument number to use for the join string using something like C<*2$v>; for example: printf '%*4$vX %*4$vX %*4$vX', @addr[1..3], ":"; # 3 IPv6 addresses =item (minimum) width Arguments are usually formatted to be only as wide as required to display the given value. You can override the width by putting a number here, or get the width from the next argument (with C<*>) or from a specified argument (e.g., with C<*2$>): printf "<%s>", "a"; # prints "<a>" printf "<%6s>", "a"; # prints "< a>" printf "<%*s>", 6, "a"; # prints "< a>" printf "<%*2$s>", "a", 6; # prints "< a>" printf "<%2s>", "long"; # prints "<long>" (does not truncate) If a field width obtained through C<*> is negative, it has the same effect as the C<-> flag: left-justification. =item precision, or maximum width X<precision> You can specify a precision (for numeric conversions) or a maximum width (for string conversions) by specifying a C<.> followed by a number. For floating-point formats except C<g> and C<G>, this specifies how many places right of the decimal point to show (the default being 6). For example: # these examples are subject to system-specific variation printf '<%f>', 1; # prints "<1.000000>" printf '<%.1f>', 1; # prints "<1.0>" printf '<%.0f>', 1; # prints "<1>" printf '<%e>', 10; # prints "<1.000000e+01>" printf '<%.1e>', 10; # prints "<1.0e+01>" For "g" and "G", this specifies the maximum number of digits to show, including those prior to the decimal point and those after it; for example: # These examples are subject to system-specific variation. printf '<%g>', 1; # prints "<1>" printf '<%.10g>', 1; # prints "<1>" printf '<%g>', 100; # prints "<100>" printf '<%.1g>', 100; # prints "<1e+02>" printf '<%.2g>', 100.01; # prints "<1e+02>" printf '<%.5g>', 100.01; # prints "<100.01>" printf '<%.4g>', 100.01; # prints "<100>" For integer conversions, specifying a precision implies that the output of the number itself should be zero-padded to this width, where the 0 flag is ignored: printf '<%.6d>', 1; # prints "<000001>" printf '<%+.6d>', 1; # prints "<+000001>" printf '<%-10.6d>', 1; # prints "<000001 >" printf '<%10.6d>', 1; # prints "< 000001>" printf '<%010.6d>', 1; # prints "< 000001>" printf '<%+10.6d>', 1; # prints "< +000001>" printf '<%.6x>', 1; # prints "<000001>" printf '<%#.6x>', 1; # prints "<0x000001>" printf '<%-10.6x>', 1; # prints "<000001 >" printf '<%10.6x>', 1; # prints "< 000001>" printf '<%010.6x>', 1; # prints "< 000001>" printf '<%#10.6x>', 1; # prints "< 0x000001>" For string conversions, specifying a precision truncates the string to fit the specified width: printf '<%.5s>', "truncated"; # prints "<trunc>" printf '<%10.5s>', "truncated"; # prints "< trunc>" You can also get the precision from the next argument using C<.*>: printf '<%.6x>', 1; # prints "<000001>" printf '<%.*x>', 6, 1; # prints "<000001>" If a precision obtained through C<*> is negative, it counts as having no precision at all. printf '<%.*s>', 7, "string"; # prints "<string>" printf '<%.*s>', 3, "string"; # prints "<str>" printf '<%.*s>', 0, "string"; # prints "<>" printf '<%.*s>', -1, "string"; # prints "<string>" printf '<%.*d>', 1, 0; # prints "<0>" printf '<%.*d>', 0, 0; # prints "<>" printf '<%.*d>', -1, 0; # prints "<0>" You cannot currently get the precision from a specified number, but it is intended that this will be possible in the future, for example using C<.*2$>: printf "<%.*2$x>", 1, 6; # INVALID, but in future will print "<000001>" =item size For numeric conversions, you can specify the size to interpret the number as using C<l>, C<h>, C<V>, C<q>, C<L>, or C<ll>. For integer conversions (C<d u o x X b i D U O>), numbers are usually assumed to be whatever the default integer size is on your platform (usually 32 or 64 bits), but you can override this to use instead one of the standard C types, as supported by the compiler used to build Perl: hh interpret integer as C type "char" or "unsigned char" on Perl 5.14 or later h interpret integer as C type "short" or "unsigned short" j interpret integer as C type "intmax_t" on Perl 5.14 or later, and only with a C99 compiler (unportable) l interpret integer as C type "long" or "unsigned long" q, L, or ll interpret integer as C type "long long", "unsigned long long", or "quad" (typically 64-bit integers) t interpret integer as C type "ptrdiff_t" on Perl 5.14 or later z interpret integer as C type "size_t" on Perl 5.14 or later As of 5.14, none of these raises an exception if they are not supported on your platform. However, if warnings are enabled, a warning of the C<printf> warning class is issued on an unsupported conversion flag. Should you instead prefer an exception, do this: use warnings FATAL => "printf"; If you would like to know about a version dependency before you start running the program, put something like this at its top: use 5.014; # for hh/j/t/z/ printf modifiers You can find out whether your Perl supports quads via L<Config>: use Config; if ($Config{use64bitint} eq "define" || $Config{longsize} >= 8) { print "Nice quads!\n"; } For floating-point conversions (C<e f g E F G>), numbers are usually assumed to be the default floating-point size on your platform (double or long double), but you can force "long double" with C<q>, C<L>, or C<ll> if your platform supports them. You can find out whether your Perl supports long doubles via L<Config>: use Config; print "long doubles\n" if $Config{d_longdbl} eq "define"; You can find out whether Perl considers "long double" to be the default floating-point size to use on your platform via L<Config>: use Config; if ($Config{uselongdouble} eq "define") { print "long doubles by default\n"; } It can also be that long doubles and doubles are the same thing: use Config; ($Config{doublesize} == $Config{longdblsize}) && print "doubles are long doubles\n"; The size specifier C<V> has no effect for Perl code, but is supported for compatibility with XS code. It means "use the standard size for a Perl integer or floating-point number", which is the default. =item order of arguments Normally, sprintf() takes the next unused argument as the value to format for each format specification. If the format specification uses C<*> to require additional arguments, these are consumed from the argument list in the order they appear in the format specification I<before> the value to format. Where an argument is specified by an explicit index, this does not affect the normal order for the arguments, even when the explicitly specified index would have been the next argument. So: printf "<%*.*s>", $a, $b, $c; uses C<$a> for the width, C<$b> for the precision, and C<$c> as the value to format; while: printf "<%*1$.*s>", $a, $b; would use C<$a> for the width and precision, and C<$b> as the value to format. Here are some more examples; be aware that when using an explicit index, the C<$> may need escaping: printf "%2\$d %d\n", 12, 34; # will print "34 12\n" printf "%2\$d %d %d\n", 12, 34; # will print "34 12 34\n" printf "%3\$d %d %d\n", 12, 34, 56; # will print "56 12 34\n" printf "%2\$*3\$d %d\n", 12, 34, 3; # will print " 34 12\n" =back If C<use locale> (including C<use locale 'not_characters'>) is in effect and POSIX::setlocale() has been called, the character used for the decimal separator in formatted floating-point numbers is affected by the LC_NUMERIC locale. See L<perllocale> and L<POSIX>. =item sqrt EXPR X<sqrt> X<root> X<square root> =item sqrt =for Pod::Functions square root function Return the positive square root of EXPR. If EXPR is omitted, uses C<$_>. Works only for non-negative operands unless you've loaded the C<Math::Complex> module. use Math::Complex; print sqrt(-4); # prints 2i =item srand EXPR X<srand> X<seed> X<randseed> =item srand =for Pod::Functions seed the random number generator Sets and returns the random number seed for the C<rand> operator. The point of the function is to "seed" the C<rand> function so that C<rand> can produce a different sequence each time you run your program. When called with a parameter, C<srand> uses that for the seed; otherwise it (semi-)randomly chooses a seed. In either case, starting with Perl 5.14, it returns the seed. To signal that your code will work I<only> on Perls of a recent vintage: use 5.014; # so srand returns the seed If C<srand()> is not called explicitly, it is called implicitly without a parameter at the first use of the C<rand> operator. However, this was not true of versions of Perl before 5.004, so if your script will run under older Perl versions, it should call C<srand>; otherwise most programs won't call C<srand()> at all. But there are a few situations in recent Perls where programs are likely to want to call C<srand>. One is for generating predictable results generally for testing or debugging. There, you use C<srand($seed)>, with the same C<$seed> each time. Another case is that you may want to call C<srand()> after a C<fork()> to avoid child processes sharing the same seed value as the parent (and consequently each other). Do B<not> call C<srand()> (i.e., without an argument) more than once per process. The internal state of the random number generator should contain more entropy than can be provided by any seed, so calling C<srand()> again actually I<loses> randomness. Most implementations of C<srand> take an integer and will silently truncate decimal numbers. This means C<srand(42)> will usually produce the same results as C<srand(42.1)>. To be safe, always pass C<srand> an integer. In versions of Perl prior to 5.004 the default seed was just the current C<time>. This isn't a particularly good seed, so many old programs supply their own seed value (often C<time ^ $$> or C<time ^ ($$ + ($$ << 15))>), but that isn't necessary any more. Frequently called programs (like CGI scripts) that simply use time ^ $$ for a seed can fall prey to the mathematical property that a^b == (a+1)^(b+1) one-third of the time. So don't do that. A typical use of the returned seed is for a test program which has too many combinations to test comprehensively in the time available to it each run. It can test a random subset each time, and should there be a failure, log the seed used for that run so that it can later be used to reproduce the same results. B<C<rand()> is not cryptographically secure. You should not rely on it in security-sensitive situations.> As of this writing, a number of third-party CPAN modules offer random number generators intended by their authors to be cryptographically secure, including: L<Data::Entropy>, L<Crypt::Random>, L<Math::Random::Secure>, and L<Math::TrulyRandom>. =item stat FILEHANDLE X<stat> X<file, status> X<ctime> =item stat EXPR =item stat DIRHANDLE =item stat =for Pod::Functions get a file's status information Returns a 13-element list giving the status info for a file, either the file opened via FILEHANDLE or DIRHANDLE, or named by EXPR. If EXPR is omitted, it stats C<$_> (not C<_>!). Returns the empty list if C<stat> fails. Typically used as follows: ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size, $atime,$mtime,$ctime,$blksize,$blocks) = stat($filename); Not all fields are supported on all filesystem types. Here are the meanings of the fields: 0 dev device number of filesystem 1 ino inode number 2 mode file mode (type and permissions) 3 nlink number of (hard) links to the file 4 uid numeric user ID of file's owner 5 gid numeric group ID of file's owner 6 rdev the device identifier (special files only) 7 size total size of file, in bytes 8 atime last access time in seconds since the epoch 9 mtime last modify time in seconds since the epoch 10 ctime inode change time in seconds since the epoch (*) 11 blksize preferred block size for file system I/O 12 blocks actual number of blocks allocated (The epoch was at 00:00 January 1, 1970 GMT.) (*) Not all fields are supported on all filesystem types. Notably, the ctime field is non-portable. In particular, you cannot expect it to be a "creation time"; see L<perlport/"Files and Filesystems"> for details. If C<stat> is passed the special filehandle consisting of an underline, no stat is done, but the current contents of the stat structure from the last C<stat>, C<lstat>, or filetest are returned. Example: if (-x $file && (($d) = stat(_)) && $d < 0) { print "$file is executable NFS file\n"; } (This works on machines only for which the device number is negative under NFS.) Because the mode contains both the file type and its permissions, you should mask off the file type portion and (s)printf using a C<"%o"> if you want to see the real permissions. $mode = (stat($filename))[2]; printf "Permissions are %04o\n", $mode & 07777; In scalar context, C<stat> returns a boolean value indicating success or failure, and, if successful, sets the information associated with the special filehandle C<_>. The L<File::stat> module provides a convenient, by-name access mechanism: use File::stat; $sb = stat($filename); printf "File is %s, size is %s, perm %04o, mtime %s\n", $filename, $sb->size, $sb->mode & 07777, scalar localtime $sb->mtime; You can import symbolic mode constants (C<S_IF*>) and functions (C<S_IS*>) from the Fcntl module: use Fcntl ':mode'; $mode = (stat($filename))[2]; $user_rwx = ($mode & S_IRWXU) >> 6; $group_read = ($mode & S_IRGRP) >> 3; $other_execute = $mode & S_IXOTH; printf "Permissions are %04o\n", S_IMODE($mode), "\n"; $is_setuid = $mode & S_ISUID; $is_directory = S_ISDIR($mode); You could write the last two using the C<-u> and C<-d> operators. Commonly available C<S_IF*> constants are: # Permissions: read, write, execute, for user, group, others. S_IRWXU S_IRUSR S_IWUSR S_IXUSR S_IRWXG S_IRGRP S_IWGRP S_IXGRP S_IRWXO S_IROTH S_IWOTH S_IXOTH # Setuid/Setgid/Stickiness/SaveText. # Note that the exact meaning of these is system-dependent. S_ISUID S_ISGID S_ISVTX S_ISTXT # File types. Not all are necessarily available on # your system. S_IFREG S_IFDIR S_IFLNK S_IFBLK S_IFCHR S_IFIFO S_IFSOCK S_IFWHT S_ENFMT # The following are compatibility aliases for S_IRUSR, # S_IWUSR, and S_IXUSR. S_IREAD S_IWRITE S_IEXEC and the C<S_IF*> functions are S_IMODE($mode) the part of $mode containing the permission bits and the setuid/setgid/sticky bits S_IFMT($mode) the part of $mode containing the file type which can be bit-anded with (for example) S_IFREG or with the following functions # The operators -f, -d, -l, -b, -c, -p, and -S. S_ISREG($mode) S_ISDIR($mode) S_ISLNK($mode) S_ISBLK($mode) S_ISCHR($mode) S_ISFIFO($mode) S_ISSOCK($mode) # No direct -X operator counterpart, but for the first one # the -g operator is often equivalent. The ENFMT stands for # record flocking enforcement, a platform-dependent feature. S_ISENFMT($mode) S_ISWHT($mode) See your native chmod(2) and stat(2) documentation for more details about the C<S_*> constants. To get status info for a symbolic link instead of the target file behind the link, use the C<lstat> function. Portability issues: L<perlport/stat>. =item state EXPR X<state> =item state TYPE EXPR =item state EXPR : ATTRS =item state TYPE EXPR : ATTRS =for Pod::Functions +state declare and assign a persistent lexical variable C<state> declares a lexically scoped variable, just like C<my>. However, those variables will never be reinitialized, contrary to lexical variables that are reinitialized each time their enclosing block is entered. See L<perlsub/"Persistent Private Variables"> for details. C<state> variables are enabled only when the C<use feature "state"> pragma is in effect, unless the keyword is written as C<CORE::state>. See also L<feature>. =item study SCALAR X<study> =item study =for Pod::Functions optimize input data for repeated searches Takes extra time to study SCALAR (C<$_> if unspecified) in anticipation of doing many pattern matches on the string before it is next modified. This may or may not save time, depending on the nature and number of patterns you are searching and the distribution of character frequencies in the string to be searched; you probably want to compare run times with and without it to see which is faster. Those loops that scan for many short constant strings (including the constant parts of more complex patterns) will benefit most. (The way C<study> works is this: a linked list of every character in the string to be searched is made, so we know, for example, where all the C<'k'> characters are. From each search string, the rarest character is selected, based on some static frequency tables constructed from some C programs and English text. Only those places that contain this "rarest" character are examined.) For example, here is a loop that inserts index producing entries before any line containing a certain pattern: while (<>) { study; print ".IX foo\n" if /\bfoo\b/; print ".IX bar\n" if /\bbar\b/; print ".IX blurfl\n" if /\bblurfl\b/; # ... print; } In searching for C</\bfoo\b/>, only locations in C<$_> that contain C<f> will be looked at, because C<f> is rarer than C<o>. In general, this is a big win except in pathological cases. The only question is whether it saves you more time than it took to build the linked list in the first place. Note that if you have to look for strings that you don't know till runtime, you can build an entire loop as a string and C<eval> that to avoid recompiling all your patterns all the time. Together with undefining C<$/> to input entire files as one record, this can be quite fast, often faster than specialized programs like fgrep(1). The following scans a list of files (C<@files>) for a list of words (C<@words>), and prints out the names of those files that contain a match: $search = 'while (<>) { study;'; foreach $word (@words) { $search .= "++\$seen{\$ARGV} if /\\b$word\\b/;\n"; } $search .= "}"; @ARGV = @files; undef $/; eval $search; # this screams $/ = "\n"; # put back to normal input delimiter foreach $file (sort keys(%seen)) { print $file, "\n"; } =item sub NAME BLOCK X<sub> =item sub NAME (PROTO) BLOCK =item sub NAME : ATTRS BLOCK =item sub NAME (PROTO) : ATTRS BLOCK =for Pod::Functions declare a subroutine, possibly anonymously This is subroutine definition, not a real function I<per se>. Without a BLOCK it's just a forward declaration. Without a NAME, it's an anonymous function declaration, so does return a value: the CODE ref of the closure just created. See L<perlsub> and L<perlref> for details about subroutines and references; see L<attributes> and L<Attribute::Handlers> for more information about attributes. =item __SUB__ X<__SUB__> =for Pod::Functions +current_sub the current subroutine, or C<undef> if not in a subroutine A special token that returns the a reference to the current subroutine, or C<undef> outside of a subroutine. This token is only available under C<use v5.16> or the "current_sub" feature. See L<feature>. =item substr EXPR,OFFSET,LENGTH,REPLACEMENT X<substr> X<substring> X<mid> X<left> X<right> =item substr EXPR,OFFSET,LENGTH =item substr EXPR,OFFSET =for Pod::Functions get or alter a portion of a string Extracts a substring out of EXPR and returns it. First character is at offset zero. If OFFSET is negative, starts that far back from the end of the string. If LENGTH is omitted, returns everything through the end of the string. If LENGTH is negative, leaves that many characters off the end of the string. my $s = "The black cat climbed the green tree"; my $color = substr $s, 4, 5; # black my $middle = substr $s, 4, -11; # black cat climbed the my $end = substr $s, 14; # climbed the green tree my $tail = substr $s, -4; # tree my $z = substr $s, -4, 2; # tr You can use the substr() function as an lvalue, in which case EXPR must itself be an lvalue. If you assign something shorter than LENGTH, the string will shrink, and if you assign something longer than LENGTH, the string will grow to accommodate it. To keep the string the same length, you may need to pad or chop your value using C<sprintf>. If OFFSET and LENGTH specify a substring that is partly outside the string, only the part within the string is returned. If the substring is beyond either end of the string, substr() returns the undefined value and produces a warning. When used as an lvalue, specifying a substring that is entirely outside the string raises an exception. Here's an example showing the behavior for boundary cases: my $name = 'fred'; substr($name, 4) = 'dy'; # $name is now 'freddy' my $null = substr $name, 6, 2; # returns "" (no warning) my $oops = substr $name, 7; # returns undef, with warning substr($name, 7) = 'gap'; # raises an exception An alternative to using substr() as an lvalue is to specify the replacement string as the 4th argument. This allows you to replace parts of the EXPR and return what was there before in one operation, just as you can with splice(). my $s = "The black cat climbed the green tree"; my $z = substr $s, 14, 7, "jumped from"; # climbed # $s is now "The black cat jumped from the green tree" Note that the lvalue returned by the three-argument version of substr() acts as a 'magic bullet'; each time it is assigned to, it remembers which part of the original string is being modified; for example: $x = '1234'; for (substr($x,1,2)) { $_ = 'a'; print $x,"\n"; # prints 1a4 $_ = 'xyz'; print $x,"\n"; # prints 1xyz4 $x = '56789'; $_ = 'pq'; print $x,"\n"; # prints 5pq9 } With negative offsets, it remembers its position from the end of the string when the target string is modified: $x = '1234'; for (substr($x, -3, 2)) { $_ = 'a'; print $x,"\n"; # prints 1a4, as above $x = 'abcdefg'; print $_,"\n"; # prints f } Prior to Perl version 5.10, the result of using an lvalue multiple times was unspecified. Prior to 5.16, the result with negative offsets was unspecified. =item symlink OLDFILE,NEWFILE X<symlink> X<link> X<symbolic link> X<link, symbolic> =for Pod::Functions create a symbolic link to a file Creates a new filename symbolically linked to the old filename. Returns C<1> for success, C<0> otherwise. On systems that don't support symbolic links, raises an exception. To check for that, use eval: $symlink_exists = eval { symlink("",""); 1 }; Portability issues: L<perlport/symlink>. =item syscall NUMBER, LIST X<syscall> X<system call> =for Pod::Functions execute an arbitrary system call Calls the system call specified as the first element of the list, passing the remaining elements as arguments to the system call. If unimplemented, raises an exception. The arguments are interpreted as follows: if a given argument is numeric, the argument is passed as an int. If not, the pointer to the string value is passed. You are responsible to make sure a string is pre-extended long enough to receive any result that might be written into a string. You can't use a string literal (or other read-only string) as an argument to C<syscall> because Perl has to assume that any string pointer might be written through. If your integer arguments are not literals and have never been interpreted in a numeric context, you may need to add C<0> to them to force them to look like numbers. This emulates the C<syswrite> function (or vice versa): require 'syscall.ph'; # may need to run h2ph $s = "hi there\n"; syscall(&SYS_write, fileno(STDOUT), $s, length $s); Note that Perl supports passing of up to only 14 arguments to your syscall, which in practice should (usually) suffice. Syscall returns whatever value returned by the system call it calls. If the system call fails, C<syscall> returns C<-1> and sets C<$!> (errno). Note that some system calls I<can> legitimately return C<-1>. The proper way to handle such calls is to assign C<$!=0> before the call, then check the value of C<$!> if C<syscall> returns C<-1>. There's a problem with C<syscall(&SYS_pipe)>: it returns the file number of the read end of the pipe it creates, but there is no way to retrieve the file number of the other end. You can avoid this problem by using C<pipe> instead. Portability issues: L<perlport/syscall>. =item sysopen FILEHANDLE,FILENAME,MODE X<sysopen> =item sysopen FILEHANDLE,FILENAME,MODE,PERMS =for Pod::Functions +5.002 open a file, pipe, or descriptor Opens the file whose filename is given by FILENAME, and associates it with FILEHANDLE. If FILEHANDLE is an expression, its value is used as the real filehandle wanted; an undefined scalar will be suitably autovivified. This function calls the underlying operating system's I<open>(2) function with the parameters FILENAME, MODE, and PERMS. The possible values and flag bits of the MODE parameter are system-dependent; they are available via the standard module C<Fcntl>. See the documentation of your operating system's I<open>(2) syscall to see which values and flag bits are available. You may combine several flags using the C<|>-operator. Some of the most common values are C<O_RDONLY> for opening the file in read-only mode, C<O_WRONLY> for opening the file in write-only mode, and C<O_RDWR> for opening the file in read-write mode. X<O_RDONLY> X<O_RDWR> X<O_WRONLY> For historical reasons, some values work on almost every system supported by Perl: 0 means read-only, 1 means write-only, and 2 means read/write. We know that these values do I<not> work under OS/390 & VM/ESA Unix and on the Macintosh; you probably don't want to use them in new code. If the file named by FILENAME does not exist and the C<open> call creates it (typically because MODE includes the C<O_CREAT> flag), then the value of PERMS specifies the permissions of the newly created file. If you omit the PERMS argument to C<sysopen>, Perl uses the octal value C<0666>. These permission values need to be in octal, and are modified by your process's current C<umask>. X<O_CREAT> In many systems the C<O_EXCL> flag is available for opening files in exclusive mode. This is B<not> locking: exclusiveness means here that if the file already exists, sysopen() fails. C<O_EXCL> may not work on network filesystems, and has no effect unless the C<O_CREAT> flag is set as well. Setting C<O_CREAT|O_EXCL> prevents the file from being opened if it is a symbolic link. It does not protect against symbolic links in the file's path. X<O_EXCL> Sometimes you may want to truncate an already-existing file. This can be done using the C<O_TRUNC> flag. The behavior of C<O_TRUNC> with C<O_RDONLY> is undefined. X<O_TRUNC> You should seldom if ever use C<0644> as argument to C<sysopen>, because that takes away the user's option to have a more permissive umask. Better to omit it. See the perlfunc(1) entry on C<umask> for more on this. Note that C<sysopen> depends on the fdopen() C library function. On many Unix systems, fdopen() is known to fail when file descriptors exceed a certain value, typically 255. If you need more file descriptors than that, consider rebuilding Perl to use the C<sfio> library, or perhaps using the POSIX::open() function. See L<perlopentut> for a kinder, gentler explanation of opening files. Portability issues: L<perlport/sysopen>. =item sysread FILEHANDLE,SCALAR,LENGTH,OFFSET X<sysread> =item sysread FILEHANDLE,SCALAR,LENGTH =for Pod::Functions fixed-length unbuffered input from a filehandle Attempts to read LENGTH bytes of data into variable SCALAR from the specified FILEHANDLE, using the read(2). It bypasses buffered IO, so mixing this with other kinds of reads, C<print>, C<write>, C<seek>, C<tell>, or C<eof> can cause confusion because the perlio or stdio layers usually buffers data. Returns the number of bytes actually read, C<0> at end of file, or undef if there was an error (in the latter case C<$!> is also set). SCALAR will be grown or shrunk so that the last byte actually read is the last byte of the scalar after the read. An OFFSET may be specified to place the read data at some place in the string other than the beginning. A negative OFFSET specifies placement at that many characters counting backwards from the end of the string. A positive OFFSET greater than the length of SCALAR results in the string being padded to the required size with C<"\0"> bytes before the result of the read is appended. There is no syseof() function, which is ok, since eof() doesn't work well on device files (like ttys) anyway. Use sysread() and check for a return value for 0 to decide whether you're done. Note that if the filehandle has been marked as C<:utf8> Unicode characters are read instead of bytes (the LENGTH, OFFSET, and the return value of sysread() are in Unicode characters). The C<:encoding(...)> layer implicitly introduces the C<:utf8> layer. See L</binmode>, L</open>, and the C<open> pragma, L<open>. =item sysseek FILEHANDLE,POSITION,WHENCE X<sysseek> X<lseek> =for Pod::Functions +5.004 position I/O pointer on handle used with sysread and syswrite Sets FILEHANDLE's system position in bytes using lseek(2). FILEHANDLE may be an expression whose value gives the name of the filehandle. The values for WHENCE are C<0> to set the new position to POSITION; C<1> to set the it to the current position plus POSITION; and C<2> to set it to EOF plus POSITION, typically negative. Note the I<in bytes>: even if the filehandle has been set to operate on characters (for example by using the C<:encoding(utf8)> I/O layer), tell() will return byte offsets, not character offsets (because implementing that would render sysseek() unacceptably slow). sysseek() bypasses normal buffered IO, so mixing it with reads other than C<sysread> (for example C<< <> >> or read()) C<print>, C<write>, C<seek>, C<tell>, or C<eof> may cause confusion. For WHENCE, you may also use the constants C<SEEK_SET>, C<SEEK_CUR>, and C<SEEK_END> (start of the file, current position, end of the file) from the Fcntl module. Use of the constants is also more portable than relying on 0, 1, and 2. For example to define a "systell" function: use Fcntl 'SEEK_CUR'; sub systell { sysseek($_[0], 0, SEEK_CUR) } Returns the new position, or the undefined value on failure. A position of zero is returned as the string C<"0 but true">; thus C<sysseek> returns true on success and false on failure, yet you can still easily determine the new position. =item system LIST X<system> X<shell> =item system PROGRAM LIST =for Pod::Functions run a separate program Does exactly the same thing as C<exec LIST>, except that a fork is done first and the parent process waits for the child process to exit. Note that argument processing varies depending on the number of arguments. If there is more than one argument in LIST, or if LIST is an array with more than one value, starts the program given by the first element of the list with arguments given by the rest of the list. If there is only one scalar argument, the argument is checked for shell metacharacters, and if there are any, the entire argument is passed to the system's command shell for parsing (this is C</bin/sh -c> on Unix platforms, but varies on other platforms). If there are no shell metacharacters in the argument, it is split into words and passed directly to C<execvp>, which is more efficient. Beginning with v5.6.0, Perl will attempt to flush all files opened for output before any operation that may do a fork, but this may not be supported on some platforms (see L<perlport>). To be safe, you may need to set C<$|> ($AUTOFLUSH in English) or call the C<autoflush()> method of C<IO::Handle> on any open handles. The return value is the exit status of the program as returned by the C<wait> call. To get the actual exit value, shift right by eight (see below). See also L</exec>. This is I<not> what you want to use to capture the output from a command; for that you should use merely backticks or C<qx//>, as described in L<perlop/"`STRING`">. Return value of -1 indicates a failure to start the program or an error of the wait(2) system call (inspect $! for the reason). If you'd like to make C<system> (and many other bits of Perl) die on error, have a look at the L<autodie> pragma. Like C<exec>, C<system> allows you to lie to a program about its name if you use the C<system PROGRAM LIST> syntax. Again, see L</exec>. Since C<SIGINT> and C<SIGQUIT> are ignored during the execution of C<system>, if you expect your program to terminate on receipt of these signals you will need to arrange to do so yourself based on the return value. @args = ("command", "arg1", "arg2"); system(@args) == 0 or die "system @args failed: $?" If you'd like to manually inspect C<system>'s failure, you can check all possible failure modes by inspecting C<$?> like this: if ($? == -1) { print "failed to execute: $!\n"; } elsif ($? & 127) { printf "child died with signal %d, %s coredump\n", ($? & 127), ($? & 128) ? 'with' : 'without'; } else { printf "child exited with value %d\n", $? >> 8; } Alternatively, you may inspect the value of C<${^CHILD_ERROR_NATIVE}> with the C<W*()> calls from the POSIX module. When C<system>'s arguments are executed indirectly by the shell, results and return codes are subject to its quirks. See L<perlop/"`STRING`"> and L</exec> for details. Since C<system> does a C<fork> and C<wait> it may affect a C<SIGCHLD> handler. See L<perlipc> for details. Portability issues: L<perlport/system>. =item syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET X<syswrite> =item syswrite FILEHANDLE,SCALAR,LENGTH =item syswrite FILEHANDLE,SCALAR =for Pod::Functions fixed-length unbuffered output to a filehandle Attempts to write LENGTH bytes of data from variable SCALAR to the specified FILEHANDLE, using write(2). If LENGTH is not specified, writes whole SCALAR. It bypasses buffered IO, so mixing this with reads (other than C<sysread())>, C<print>, C<write>, C<seek>, C<tell>, or C<eof> may cause confusion because the perlio and stdio layers usually buffer data. Returns the number of bytes actually written, or C<undef> if there was an error (in this case the errno variable C<$!> is also set). If the LENGTH is greater than the data available in the SCALAR after the OFFSET, only as much data as is available will be written. An OFFSET may be specified to write the data from some part of the string other than the beginning. A negative OFFSET specifies writing that many characters counting backwards from the end of the string. If SCALAR is of length zero, you can only use an OFFSET of 0. B<WARNING>: If the filehandle is marked C<:utf8>, Unicode characters encoded in UTF-8 are written instead of bytes, and the LENGTH, OFFSET, and return value of syswrite() are in (UTF8-encoded Unicode) characters. The C<:encoding(...)> layer implicitly introduces the C<:utf8> layer. Alternately, if the handle is not marked with an encoding but you attempt to write characters with code points over 255, raises an exception. See L</binmode>, L</open>, and the C<open> pragma, L<open>. =item tell FILEHANDLE X<tell> =item tell =for Pod::Functions get current seekpointer on a filehandle Returns the current position I<in bytes> for FILEHANDLE, or -1 on error. FILEHANDLE may be an expression whose value gives the name of the actual filehandle. If FILEHANDLE is omitted, assumes the file last read. Note the I<in bytes>: even if the filehandle has been set to operate on characters (for example by using the C<:encoding(utf8)> open layer), tell() will return byte offsets, not character offsets (because that would render seek() and tell() rather slow). The return value of tell() for the standard streams like the STDIN depends on the operating system: it may return -1 or something else. tell() on pipes, fifos, and sockets usually returns -1. There is no C<systell> function. Use C<sysseek(FH, 0, 1)> for that. Do not use tell() (or other buffered I/O operations) on a filehandle that has been manipulated by sysread(), syswrite(), or sysseek(). Those functions ignore the buffering, while tell() does not. =item telldir DIRHANDLE X<telldir> =for Pod::Functions get current seekpointer on a directory handle Returns the current position of the C<readdir> routines on DIRHANDLE. Value may be given to C<seekdir> to access a particular location in a directory. C<telldir> has the same caveats about possible directory compaction as the corresponding system library routine. =item tie VARIABLE,CLASSNAME,LIST X<tie> =for Pod::Functions +5.002 bind a variable to an object class This function binds a variable to a package class that will provide the implementation for the variable. VARIABLE is the name of the variable to be enchanted. CLASSNAME is the name of a class implementing objects of correct type. Any additional arguments are passed to the C<new> method of the class (meaning C<TIESCALAR>, C<TIEHANDLE>, C<TIEARRAY>, or C<TIEHASH>). Typically these are arguments such as might be passed to the C<dbm_open()> function of C. The object returned by the C<new> method is also returned by the C<tie> function, which would be useful if you want to access other methods in CLASSNAME. Note that functions such as C<keys> and C<values> may return huge lists when used on large objects, like DBM files. You may prefer to use the C<each> function to iterate over such. Example: # print out history file offsets use NDBM_File; tie(%HIST, 'NDBM_File', '/usr/lib/news/history', 1, 0); while (($key,$val) = each %HIST) { print $key, ' = ', unpack('L',$val), "\n"; } untie(%HIST); A class implementing a hash should have the following methods: TIEHASH classname, LIST FETCH this, key STORE this, key, value DELETE this, key CLEAR this EXISTS this, key FIRSTKEY this NEXTKEY this, lastkey SCALAR this DESTROY this UNTIE this A class implementing an ordinary array should have the following methods: TIEARRAY classname, LIST FETCH this, key STORE this, key, value FETCHSIZE this STORESIZE this, count CLEAR this PUSH this, LIST POP this SHIFT this UNSHIFT this, LIST SPLICE this, offset, length, LIST EXTEND this, count DESTROY this UNTIE this A class implementing a filehandle should have the following methods: TIEHANDLE classname, LIST READ this, scalar, length, offset READLINE this GETC this WRITE this, scalar, length, offset PRINT this, LIST PRINTF this, format, LIST BINMODE this EOF this FILENO this SEEK this, position, whence TELL this OPEN this, mode, LIST CLOSE this DESTROY this UNTIE this A class implementing a scalar should have the following methods: TIESCALAR classname, LIST FETCH this, STORE this, value DESTROY this UNTIE this Not all methods indicated above need be implemented. See L<perltie>, L<Tie::Hash>, L<Tie::Array>, L<Tie::Scalar>, and L<Tie::Handle>. Unlike C<dbmopen>, the C<tie> function will not C<use> or C<require> a module for you; you need to do that explicitly yourself. See L<DB_File> or the F<Config> module for interesting C<tie> implementations. For further details see L<perltie>, L<"tied VARIABLE">. =item tied VARIABLE X<tied> =for Pod::Functions get a reference to the object underlying a tied variable Returns a reference to the object underlying VARIABLE (the same value that was originally returned by the C<tie> call that bound the variable to a package.) Returns the undefined value if VARIABLE isn't tied to a package. =item time X<time> X<epoch> =for Pod::Functions return number of seconds since 1970 Returns the number of non-leap seconds since whatever time the system considers to be the epoch, suitable for feeding to C<gmtime> and C<localtime>. On most systems the epoch is 00:00:00 UTC, January 1, 1970; a prominent exception being Mac OS Classic which uses 00:00:00, January 1, 1904 in the current local time zone for its epoch. For measuring time in better granularity than one second, use the L<Time::HiRes> module from Perl 5.8 onwards (or from CPAN before then), or, if you have gettimeofday(2), you may be able to use the C<syscall> interface of Perl. See L<perlfaq8> for details. For date and time processing look at the many related modules on CPAN. For a comprehensive date and time representation look at the L<DateTime> module. =item times X<times> =for Pod::Functions return elapsed time for self and child processes Returns a four-element list giving the user and system times in seconds for this process and any exited children of this process. ($user,$system,$cuser,$csystem) = times; In scalar context, C<times> returns C<$user>. Children's times are only included for terminated children. Portability issues: L<perlport/times>. =item tr/// =for Pod::Functions transliterate a string The transliteration operator. Same as C<y///>. See L<perlop/"Quote and Quote-like Operators">. =item truncate FILEHANDLE,LENGTH X<truncate> =item truncate EXPR,LENGTH =for Pod::Functions shorten a file Truncates the file opened on FILEHANDLE, or named by EXPR, to the specified length. Raises an exception if truncate isn't implemented on your system. Returns true if successful, C<undef> on error. The behavior is undefined if LENGTH is greater than the length of the file. The position in the file of FILEHANDLE is left unchanged. You may want to call L<seek|/"seek FILEHANDLE,POSITION,WHENCE"> before writing to the file. Portability issues: L<perlport/truncate>. =item uc EXPR X<uc> X<uppercase> X<toupper> =item uc =for Pod::Functions return upper-case version of a string Returns an uppercased version of EXPR. This is the internal function implementing the C<\U> escape in double-quoted strings. It does not attempt to do titlecase mapping on initial letters. See L</ucfirst> for that. If EXPR is omitted, uses C<$_>. This function behaves the same way under various pragma, such as in a locale, as L</lc> does. =item ucfirst EXPR X<ucfirst> X<uppercase> =item ucfirst =for Pod::Functions return a string with just the next letter in upper case Returns the value of EXPR with the first character in uppercase (titlecase in Unicode). This is the internal function implementing the C<\u> escape in double-quoted strings. If EXPR is omitted, uses C<$_>. This function behaves the same way under various pragma, such as in a locale, as L</lc> does. =item umask EXPR X<umask> =item umask =for Pod::Functions set file creation mode mask Sets the umask for the process to EXPR and returns the previous value. If EXPR is omitted, merely returns the current umask. The Unix permission C<rwxr-x---> is represented as three sets of three bits, or three octal digits: C<0750> (the leading 0 indicates octal and isn't one of the digits). The C<umask> value is such a number representing disabled permissions bits. The permission (or "mode") values you pass C<mkdir> or C<sysopen> are modified by your umask, so even if you tell C<sysopen> to create a file with permissions C<0777>, if your umask is C<0022>, then the file will actually be created with permissions C<0755>. If your C<umask> were C<0027> (group can't write; others can't read, write, or execute), then passing C<sysopen> C<0666> would create a file with mode C<0640> (because C<0666 &~ 027> is C<0640>). Here's some advice: supply a creation mode of C<0666> for regular files (in C<sysopen>) and one of C<0777> for directories (in C<mkdir>) and executable files. This gives users the freedom of choice: if they want protected files, they might choose process umasks of C<022>, C<027>, or even the particularly antisocial mask of C<077>. Programs should rarely if ever make policy decisions better left to the user. The exception to this is when writing files that should be kept private: mail files, web browser cookies, I<.rhosts> files, and so on. If umask(2) is not implemented on your system and you are trying to restrict access for I<yourself> (i.e., C<< (EXPR & 0700) > 0 >>), raises an exception. If umask(2) is not implemented and you are not trying to restrict access for yourself, returns C<undef>. Remember that a umask is a number, usually given in octal; it is I<not> a string of octal digits. See also L</oct>, if all you have is a string. Portability issues: L<perlport/umask>. =item undef EXPR X<undef> X<undefine> =item undef =for Pod::Functions remove a variable or function definition Undefines the value of EXPR, which must be an lvalue. Use only on a scalar value, an array (using C<@>), a hash (using C<%>), a subroutine (using C<&>), or a typeglob (using C<*>). Saying C<undef $hash{$key}> will probably not do what you expect on most predefined variables or DBM list values, so don't do that; see L</delete>. Always returns the undefined value. You can omit the EXPR, in which case nothing is undefined, but you still get an undefined value that you could, for instance, return from a subroutine, assign to a variable, or pass as a parameter. Examples: undef $foo; undef $bar{'blurfl'}; # Compare to: delete $bar{'blurfl'}; undef @ary; undef %hash; undef &mysub; undef *xyz; # destroys $xyz, @xyz, %xyz, &xyz, etc. return (wantarray ? (undef, $errmsg) : undef) if $they_blew_it; select undef, undef, undef, 0.25; ($a, $b, undef, $c) = &foo; # Ignore third value returned Note that this is a unary operator, not a list operator. =item unlink LIST X<unlink> X<delete> X<remove> X<rm> X<del> =item unlink =for Pod::Functions remove one link to a file Deletes a list of files. On success, it returns the number of files it successfully deleted. On failure, it returns false and sets C<$!> (errno): my $unlinked = unlink 'a', 'b', 'c'; unlink @goners; unlink glob "*.bak"; On error, C<unlink> will not tell you which files it could not remove. If you want to know which files you could not remove, try them one at a time: foreach my $file ( @goners ) { unlink $file or warn "Could not unlink $file: $!"; } Note: C<unlink> will not attempt to delete directories unless you are superuser and the B<-U> flag is supplied to Perl. Even if these conditions are met, be warned that unlinking a directory can inflict damage on your filesystem. Finally, using C<unlink> on directories is not supported on many operating systems. Use C<rmdir> instead. If LIST is omitted, C<unlink> uses C<$_>. =item unpack TEMPLATE,EXPR X<unpack> =item unpack TEMPLATE =for Pod::Functions convert binary structure into normal perl variables C<unpack> does the reverse of C<pack>: it takes a string and expands it out into a list of values. (In scalar context, it returns merely the first value produced.) If EXPR is omitted, unpacks the C<$_> string. See L<perlpacktut> for an introduction to this function. The string is broken into chunks described by the TEMPLATE. Each chunk is converted separately to a value. Typically, either the string is a result of C<pack>, or the characters of the string represent a C structure of some kind. The TEMPLATE has the same format as in the C<pack> function. Here's a subroutine that does substring: sub substr { my($what,$where,$howmuch) = @_; unpack("x$where a$howmuch", $what); } and then there's sub ordinal { unpack("W",$_[0]); } # same as ord() In addition to fields allowed in pack(), you may prefix a field with a %<number> to indicate that you want a <number>-bit checksum of the items instead of the items themselves. Default is a 16-bit checksum. Checksum is calculated by summing numeric values of expanded values (for string fields the sum of C<ord($char)> is taken; for bit fields the sum of zeroes and ones). For example, the following computes the same number as the System V sum program: $checksum = do { local $/; # slurp! unpack("%32W*",<>) % 65535; }; The following efficiently counts the number of set bits in a bit vector: $setbits = unpack("%32b*", $selectmask); The C<p> and C<P> formats should be used with care. Since Perl has no way of checking whether the value passed to C<unpack()> corresponds to a valid memory location, passing a pointer value that's not known to be valid is likely to have disastrous consequences. If there are more pack codes or if the repeat count of a field or a group is larger than what the remainder of the input string allows, the result is not well defined: the repeat count may be decreased, or C<unpack()> may produce empty strings or zeros, or it may raise an exception. If the input string is longer than one described by the TEMPLATE, the remainder of that input string is ignored. See L</pack> for more examples and notes. =item unshift ARRAY,LIST X<unshift> =item unshift EXPR,LIST =for Pod::Functions prepend more elements to the beginning of a list Does the opposite of a C<shift>. Or the opposite of a C<push>, depending on how you look at it. Prepends list to the front of the array and returns the new number of elements in the array. unshift(@ARGV, '-e') unless $ARGV[0] =~ /^-/; Note the LIST is prepended whole, not one element at a time, so the prepended elements stay in the same order. Use C<reverse> to do the reverse. Starting with Perl 5.14, C<unshift> can take a scalar EXPR, which must hold a reference to an unblessed array. The argument will be dereferenced automatically. This aspect of C<unshift> is considered highly experimental. The exact behaviour may change in a future version of Perl. To avoid confusing would-be users of your code who are running earlier versions of Perl with mysterious syntax errors, put this sort of thing at the top of your file to signal that your code will work I<only> on Perls of a recent vintage: use 5.014; # so push/pop/etc work on scalars (experimental) =item untie VARIABLE X<untie> =for Pod::Functions break a tie binding to a variable Breaks the binding between a variable and a package. (See L<tie|/tie VARIABLE,CLASSNAME,LIST>.) Has no effect if the variable is not tied. =item use Module VERSION LIST X<use> X<module> X<import> =item use Module VERSION =item use Module LIST =item use Module =item use VERSION =for Pod::Functions load in a module at compile time and import its namespace Imports some semantics into the current package from the named module, generally by aliasing certain subroutine or variable names into your package. It is exactly equivalent to BEGIN { require Module; Module->import( LIST ); } except that Module I<must> be a bareword. The importation can be made conditional; see L<if>. In the peculiar C<use VERSION> form, VERSION may be either a positive decimal fraction such as 5.006, which will be compared to C<$]>, or a v-string of the form v5.6.1, which will be compared to C<$^V> (aka $PERL_VERSION). An exception is raised if VERSION is greater than the version of the current Perl interpreter; Perl will not attempt to parse the rest of the file. Compare with L</require>, which can do a similar check at run time. Symmetrically, C<no VERSION> allows you to specify that you want a version of Perl older than the specified one. Specifying VERSION as a literal of the form v5.6.1 should generally be avoided, because it leads to misleading error messages under earlier versions of Perl (that is, prior to 5.6.0) that do not support this syntax. The equivalent numeric version should be used instead. use v5.6.1; # compile time version check use 5.6.1; # ditto use 5.006_001; # ditto; preferred for backwards compatibility This is often useful if you need to check the current Perl version before C<use>ing library modules that won't work with older versions of Perl. (We try not to do this more than we have to.) C<use VERSION> also enables all features available in the requested version as defined by the C<feature> pragma, disabling any features not in the requested version's feature bundle. See L<feature>. Similarly, if the specified Perl version is greater than or equal to 5.11.0, strictures are enabled lexically as with C<use strict>. Any explicit use of C<use strict> or C<no strict> overrides C<use VERSION>, even if it comes before it. In both cases, the F<feature.pm> and F<strict.pm> files are not actually loaded. The C<BEGIN> forces the C<require> and C<import> to happen at compile time. The C<require> makes sure the module is loaded into memory if it hasn't been yet. The C<import> is not a builtin; it's just an ordinary static method call into the C<Module> package to tell the module to import the list of features back into the current package. The module can implement its C<import> method any way it likes, though most modules just choose to derive their C<import> method via inheritance from the C<Exporter> class that is defined in the C<Exporter> module. See L<Exporter>. If no C<import> method can be found then the call is skipped, even if there is an AUTOLOAD method. If you do not want to call the package's C<import> method (for instance, to stop your namespace from being altered), explicitly supply the empty list: use Module (); That is exactly equivalent to BEGIN { require Module } If the VERSION argument is present between Module and LIST, then the C<use> will call the VERSION method in class Module with the given version as an argument. The default VERSION method, inherited from the UNIVERSAL class, croaks if the given version is larger than the value of the variable C<$Module::VERSION>. Again, there is a distinction between omitting LIST (C<import> called with no arguments) and an explicit empty LIST C<()> (C<import> not called). Note that there is no comma after VERSION! Because this is a wide-open interface, pragmas (compiler directives) are also implemented this way. Currently implemented pragmas are: use constant; use diagnostics; use integer; use sigtrap qw(SEGV BUS); use strict qw(subs vars refs); use subs qw(afunc blurfl); use warnings qw(all); use sort qw(stable _quicksort _mergesort); Some of these pseudo-modules import semantics into the current block scope (like C<strict> or C<integer>, unlike ordinary modules, which import symbols into the current package (which are effective through the end of the file). Because C<use> takes effect at compile time, it doesn't respect the ordinary flow control of the code being compiled. In particular, putting a C<use> inside the false branch of a conditional doesn't prevent it from being processed. If a module or pragma only needs to be loaded conditionally, this can be done using the L<if> pragma: use if $] < 5.008, "utf8"; use if WANT_WARNINGS, warnings => qw(all); There's a corresponding C<no> declaration that unimports meanings imported by C<use>, i.e., it calls C<unimport Module LIST> instead of C<import>. It behaves just as C<import> does with VERSION, an omitted or empty LIST, or no unimport method being found. no integer; no strict 'refs'; no warnings; Care should be taken when using the C<no VERSION> form of C<no>. It is I<only> meant to be used to assert that the running Perl is of a earlier version than its argument and I<not> to undo the feature-enabling side effects of C<use VERSION>. See L<perlmodlib> for a list of standard modules and pragmas. See L<perlrun> for the C<-M> and C<-m> command-line options to Perl that give C<use> functionality from the command-line. =item utime LIST X<utime> =for Pod::Functions set a file's last access and modify times Changes the access and modification times on each file of a list of files. The first two elements of the list must be the NUMERIC access and modification times, in that order. Returns the number of files successfully changed. The inode change time of each file is set to the current time. For example, this code has the same effect as the Unix touch(1) command when the files I<already exist> and belong to the user running the program: #!/usr/bin/perl $atime = $mtime = time; utime $atime, $mtime, @ARGV; Since Perl 5.7.2, if the first two elements of the list are C<undef>, the utime(2) syscall from your C library is called with a null second argument. On most systems, this will set the file's access and modification times to the current time (i.e., equivalent to the example above) and will work even on files you don't own provided you have write permission: for $file (@ARGV) { utime(undef, undef, $file) || warn "couldn't touch $file: $!"; } Under NFS this will use the time of the NFS server, not the time of the local machine. If there is a time synchronization problem, the NFS server and local machine will have different times. The Unix touch(1) command will in fact normally use this form instead of the one shown in the first example. Passing only one of the first two elements as C<undef> is equivalent to passing a 0 and will not have the effect described when both are C<undef>. This also triggers an uninitialized warning. On systems that support futimes(2), you may pass filehandles among the files. On systems that don't support futimes(2), passing filehandles raises an exception. Filehandles must be passed as globs or glob references to be recognized; barewords are considered filenames. Portability issues: L<perlport/utime>. =item values HASH X<values> =item values ARRAY =item values EXPR =for Pod::Functions return a list of the values in a hash In list context, returns a list consisting of all the values of the named hash. In Perl 5.12 or later only, will also return a list of the values of an array; prior to that release, attempting to use an array argument will produce a syntax error. In scalar context, returns the number of values. When called on a hash, the values are returned in an apparently random order. The actual random order is subject to change in future versions of Perl, but it is guaranteed to be the same order as either the C<keys> or C<each> function would produce on the same (unmodified) hash. Since Perl 5.8.1 the ordering is different even between different runs of Perl for security reasons (see L<perlsec/"Algorithmic Complexity Attacks">). As a side effect, calling values() resets the HASH or ARRAY's internal iterator, see L</each>. (In particular, calling values() in void context resets the iterator with no other overhead. Apart from resetting the iterator, C<values @array> in list context is the same as plain C<@array>. (We recommend that you use void context C<keys @array> for this, but reasoned that taking C<values @array> out would require more documentation than leaving it in.) Note that the values are not copied, which means modifying them will modify the contents of the hash: for (values %hash) { s/foo/bar/g } # modifies %hash values for (@hash{keys %hash}) { s/foo/bar/g } # same Starting with Perl 5.14, C<values> can take a scalar EXPR, which must hold a reference to an unblessed hash or array. The argument will be dereferenced automatically. This aspect of C<values> is considered highly experimental. The exact behaviour may change in a future version of Perl. for (values $hashref) { ... } for (values $obj->get_arrayref) { ... } To avoid confusing would-be users of your code who are running earlier versions of Perl with mysterious syntax errors, put this sort of thing at the top of your file to signal that your code will work I<only> on Perls of a recent vintage: use 5.012; # so keys/values/each work on arrays use 5.014; # so keys/values/each work on scalars (experimental) See also C<keys>, C<each>, and C<sort>. =item vec EXPR,OFFSET,BITS X<vec> X<bit> X<bit vector> =for Pod::Functions test or set particular bits in a string Treats the string in EXPR as a bit vector made up of elements of width BITS and returns the value of the element specified by OFFSET as an unsigned integer. BITS therefore specifies the number of bits that are reserved for each element in the bit vector. This must be a power of two from 1 to 32 (or 64, if your platform supports that). If BITS is 8, "elements" coincide with bytes of the input string. If BITS is 16 or more, bytes of the input string are grouped into chunks of size BITS/8, and each group is converted to a number as with pack()/unpack() with big-endian formats C<n>/C<N> (and analogously for BITS==64). See L<"pack"> for details. If bits is 4 or less, the string is broken into bytes, then the bits of each byte are broken into 8/BITS groups. Bits of a byte are numbered in a little-endian-ish way, as in C<0x01>, C<0x02>, C<0x04>, C<0x08>, C<0x10>, C<0x20>, C<0x40>, C<0x80>. For example, breaking the single input byte C<chr(0x36)> into two groups gives a list C<(0x6, 0x3)>; breaking it into 4 groups gives C<(0x2, 0x1, 0x3, 0x0)>. C<vec> may also be assigned to, in which case parentheses are needed to give the expression the correct precedence as in vec($image, $max_x * $x + $y, 8) = 3; If the selected element is outside the string, the value 0 is returned. If an element off the end of the string is written to, Perl will first extend the string with sufficiently many zero bytes. It is an error to try to write off the beginning of the string (i.e., negative OFFSET). If the string happens to be encoded as UTF-8 internally (and thus has the UTF8 flag set), this is ignored by C<vec>, and it operates on the internal byte string, not the conceptual character string, even if you only have characters with values less than 256. Strings created with C<vec> can also be manipulated with the logical operators C<|>, C<&>, C<^>, and C<~>. These operators will assume a bit vector operation is desired when both operands are strings. See L<perlop/"Bitwise String Operators">. The following code will build up an ASCII string saying C<'PerlPerlPerl'>. The comments show the string after each step. Note that this code works in the same way on big-endian or little-endian machines. my $foo = ''; vec($foo, 0, 32) = 0x5065726C; # 'Perl' # $foo eq "Perl" eq "\x50\x65\x72\x6C", 32 bits print vec($foo, 0, 8); # prints 80 == 0x50 == ord('P') vec($foo, 2, 16) = 0x5065; # 'PerlPe' vec($foo, 3, 16) = 0x726C; # 'PerlPerl' vec($foo, 8, 8) = 0x50; # 'PerlPerlP' vec($foo, 9, 8) = 0x65; # 'PerlPerlPe' vec($foo, 20, 4) = 2; # 'PerlPerlPe' . "\x02" vec($foo, 21, 4) = 7; # 'PerlPerlPer' # 'r' is "\x72" vec($foo, 45, 2) = 3; # 'PerlPerlPer' . "\x0c" vec($foo, 93, 1) = 1; # 'PerlPerlPer' . "\x2c" vec($foo, 94, 1) = 1; # 'PerlPerlPerl' # 'l' is "\x6c" To transform a bit vector into a string or list of 0's and 1's, use these: $bits = unpack("b*", $vector); @bits = split(//, unpack("b*", $vector)); If you know the exact length in bits, it can be used in place of the C<*>. Here is an example to illustrate how the bits actually fall in place: #!/usr/bin/perl -wl print <<'EOT'; 0 1 2 3 unpack("V",$_) 01234567890123456789012345678901 ------------------------------------------------------------------ EOT for $w (0..3) { $width = 2**$w; for ($shift=0; $shift < $width; ++$shift) { for ($off=0; $off < 32/$width; ++$off) { $str = pack("B*", "0"x32); $bits = (1<<$shift); vec($str, $off, $width) = $bits; $res = unpack("b*",$str); $val = unpack("V", $str); write; } } } format STDOUT = vec($_,@#,@#) = @<< == @######### @>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> $off, $width, $bits, $val, $res . __END__ Regardless of the machine architecture on which it runs, the example above should print the following table: 0 1 2 3 unpack("V",$_) 01234567890123456789012345678901 ------------------------------------------------------------------ vec($_, 0, 1) = 1 == 1 10000000000000000000000000000000 vec($_, 1, 1) = 1 == 2 01000000000000000000000000000000 vec($_, 2, 1) = 1 == 4 00100000000000000000000000000000 vec($_, 3, 1) = 1 == 8 00010000000000000000000000000000 vec($_, 4, 1) = 1 == 16 00001000000000000000000000000000 vec($_, 5, 1) = 1 == 32 00000100000000000000000000000000 vec($_, 6, 1) = 1 == 64 00000010000000000000000000000000 vec($_, 7, 1) = 1 == 128 00000001000000000000000000000000 vec($_, 8, 1) = 1 == 256 00000000100000000000000000000000 vec($_, 9, 1) = 1 == 512 00000000010000000000000000000000 vec($_,10, 1) = 1 == 1024 00000000001000000000000000000000 vec($_,11, 1) = 1 == 2048 00000000000100000000000000000000 vec($_,12, 1) = 1 == 4096 00000000000010000000000000000000 vec($_,13, 1) = 1 == 8192 00000000000001000000000000000000 vec($_,14, 1) = 1 == 16384 00000000000000100000000000000000 vec($_,15, 1) = 1 == 32768 00000000000000010000000000000000 vec($_,16, 1) = 1 == 65536 00000000000000001000000000000000 vec($_,17, 1) = 1 == 131072 00000000000000000100000000000000 vec($_,18, 1) = 1 == 262144 00000000000000000010000000000000 vec($_,19, 1) = 1 == 524288 00000000000000000001000000000000 vec($_,20, 1) = 1 == 1048576 00000000000000000000100000000000 vec($_,21, 1) = 1 == 2097152 00000000000000000000010000000000 vec($_,22, 1) = 1 == 4194304 00000000000000000000001000000000 vec($_,23, 1) = 1 == 8388608 00000000000000000000000100000000 vec($_,24, 1) = 1 == 16777216 00000000000000000000000010000000 vec($_,25, 1) = 1 == 33554432 00000000000000000000000001000000 vec($_,26, 1) = 1 == 67108864 00000000000000000000000000100000 vec($_,27, 1) = 1 == 134217728 00000000000000000000000000010000 vec($_,28, 1) = 1 == 268435456 00000000000000000000000000001000 vec($_,29, 1) = 1 == 536870912 00000000000000000000000000000100 vec($_,30, 1) = 1 == 1073741824 00000000000000000000000000000010 vec($_,31, 1) = 1 == 2147483648 00000000000000000000000000000001 vec($_, 0, 2) = 1 == 1 10000000000000000000000000000000 vec($_, 1, 2) = 1 == 4 00100000000000000000000000000000 vec($_, 2, 2) = 1 == 16 00001000000000000000000000000000 vec($_, 3, 2) = 1 == 64 00000010000000000000000000000000 vec($_, 4, 2) = 1 == 256 00000000100000000000000000000000 vec($_, 5, 2) = 1 == 1024 00000000001000000000000000000000 vec($_, 6, 2) = 1 == 4096 00000000000010000000000000000000 vec($_, 7, 2) = 1 == 16384 00000000000000100000000000000000 vec($_, 8, 2) = 1 == 65536 00000000000000001000000000000000 vec($_, 9, 2) = 1 == 262144 00000000000000000010000000000000 vec($_,10, 2) = 1 == 1048576 00000000000000000000100000000000 vec($_,11, 2) = 1 == 4194304 00000000000000000000001000000000 vec($_,12, 2) = 1 == 16777216 00000000000000000000000010000000 vec($_,13, 2) = 1 == 67108864 00000000000000000000000000100000 vec($_,14, 2) = 1 == 268435456 00000000000000000000000000001000 vec($_,15, 2) = 1 == 1073741824 00000000000000000000000000000010 vec($_, 0, 2) = 2 == 2 01000000000000000000000000000000 vec($_, 1, 2) = 2 == 8 00010000000000000000000000000000 vec($_, 2, 2) = 2 == 32 00000100000000000000000000000000 vec($_, 3, 2) = 2 == 128 00000001000000000000000000000000 vec($_, 4, 2) = 2 == 512 00000000010000000000000000000000 vec($_, 5, 2) = 2 == 2048 00000000000100000000000000000000 vec($_, 6, 2) = 2 == 8192 00000000000001000000000000000000 vec($_, 7, 2) = 2 == 32768 00000000000000010000000000000000 vec($_, 8, 2) = 2 == 131072 00000000000000000100000000000000 vec($_, 9, 2) = 2 == 524288 00000000000000000001000000000000 vec($_,10, 2) = 2 == 2097152 00000000000000000000010000000000 vec($_,11, 2) = 2 == 8388608 00000000000000000000000100000000 vec($_,12, 2) = 2 == 33554432 00000000000000000000000001000000 vec($_,13, 2) = 2 == 134217728 00000000000000000000000000010000 vec($_,14, 2) = 2 == 536870912 00000000000000000000000000000100 vec($_,15, 2) = 2 == 2147483648 00000000000000000000000000000001 vec($_, 0, 4) = 1 == 1 10000000000000000000000000000000 vec($_, 1, 4) = 1 == 16 00001000000000000000000000000000 vec($_, 2, 4) = 1 == 256 00000000100000000000000000000000 vec($_, 3, 4) = 1 == 4096 00000000000010000000000000000000 vec($_, 4, 4) = 1 == 65536 00000000000000001000000000000000 vec($_, 5, 4) = 1 == 1048576 00000000000000000000100000000000 vec($_, 6, 4) = 1 == 16777216 00000000000000000000000010000000 vec($_, 7, 4) = 1 == 268435456 00000000000000000000000000001000 vec($_, 0, 4) = 2 == 2 01000000000000000000000000000000 vec($_, 1, 4) = 2 == 32 00000100000000000000000000000000 vec($_, 2, 4) = 2 == 512 00000000010000000000000000000000 vec($_, 3, 4) = 2 == 8192 00000000000001000000000000000000 vec($_, 4, 4) = 2 == 131072 00000000000000000100000000000000 vec($_, 5, 4) = 2 == 2097152 00000000000000000000010000000000 vec($_, 6, 4) = 2 == 33554432 00000000000000000000000001000000 vec($_, 7, 4) = 2 == 536870912 00000000000000000000000000000100 vec($_, 0, 4) = 4 == 4 00100000000000000000000000000000 vec($_, 1, 4) = 4 == 64 00000010000000000000000000000000 vec($_, 2, 4) = 4 == 1024 00000000001000000000000000000000 vec($_, 3, 4) = 4 == 16384 00000000000000100000000000000000 vec($_, 4, 4) = 4 == 262144 00000000000000000010000000000000 vec($_, 5, 4) = 4 == 4194304 00000000000000000000001000000000 vec($_, 6, 4) = 4 == 67108864 00000000000000000000000000100000 vec($_, 7, 4) = 4 == 1073741824 00000000000000000000000000000010 vec($_, 0, 4) = 8 == 8 00010000000000000000000000000000 vec($_, 1, 4) = 8 == 128 00000001000000000000000000000000 vec($_, 2, 4) = 8 == 2048 00000000000100000000000000000000 vec($_, 3, 4) = 8 == 32768 00000000000000010000000000000000 vec($_, 4, 4) = 8 == 524288 00000000000000000001000000000000 vec($_, 5, 4) = 8 == 8388608 00000000000000000000000100000000 vec($_, 6, 4) = 8 == 134217728 00000000000000000000000000010000 vec($_, 7, 4) = 8 == 2147483648 00000000000000000000000000000001 vec($_, 0, 8) = 1 == 1 10000000000000000000000000000000 vec($_, 1, 8) = 1 == 256 00000000100000000000000000000000 vec($_, 2, 8) = 1 == 65536 00000000000000001000000000000000 vec($_, 3, 8) = 1 == 16777216 00000000000000000000000010000000 vec($_, 0, 8) = 2 == 2 01000000000000000000000000000000 vec($_, 1, 8) = 2 == 512 00000000010000000000000000000000 vec($_, 2, 8) = 2 == 131072 00000000000000000100000000000000 vec($_, 3, 8) = 2 == 33554432 00000000000000000000000001000000 vec($_, 0, 8) = 4 == 4 00100000000000000000000000000000 vec($_, 1, 8) = 4 == 1024 00000000001000000000000000000000 vec($_, 2, 8) = 4 == 262144 00000000000000000010000000000000 vec($_, 3, 8) = 4 == 67108864 00000000000000000000000000100000 vec($_, 0, 8) = 8 == 8 00010000000000000000000000000000 vec($_, 1, 8) = 8 == 2048 00000000000100000000000000000000 vec($_, 2, 8) = 8 == 524288 00000000000000000001000000000000 vec($_, 3, 8) = 8 == 134217728 00000000000000000000000000010000 vec($_, 0, 8) = 16 == 16 00001000000000000000000000000000 vec($_, 1, 8) = 16 == 4096 00000000000010000000000000000000 vec($_, 2, 8) = 16 == 1048576 00000000000000000000100000000000 vec($_, 3, 8) = 16 == 268435456 00000000000000000000000000001000 vec($_, 0, 8) = 32 == 32 00000100000000000000000000000000 vec($_, 1, 8) = 32 == 8192 00000000000001000000000000000000 vec($_, 2, 8) = 32 == 2097152 00000000000000000000010000000000 vec($_, 3, 8) = 32 == 536870912 00000000000000000000000000000100 vec($_, 0, 8) = 64 == 64 00000010000000000000000000000000 vec($_, 1, 8) = 64 == 16384 00000000000000100000000000000000 vec($_, 2, 8) = 64 == 4194304 00000000000000000000001000000000 vec($_, 3, 8) = 64 == 1073741824 00000000000000000000000000000010 vec($_, 0, 8) = 128 == 128 00000001000000000000000000000000 vec($_, 1, 8) = 128 == 32768 00000000000000010000000000000000 vec($_, 2, 8) = 128 == 8388608 00000000000000000000000100000000 vec($_, 3, 8) = 128 == 2147483648 00000000000000000000000000000001 =item wait X<wait> =for Pod::Functions wait for any child process to die Behaves like wait(2) on your system: it waits for a child process to terminate and returns the pid of the deceased process, or C<-1> if there are no child processes. The status is returned in C<$?> and C<${^CHILD_ERROR_NATIVE}>. Note that a return value of C<-1> could mean that child processes are being automatically reaped, as described in L<perlipc>. If you use wait in your handler for $SIG{CHLD} it may accidentally for the child created by qx() or system(). See L<perlipc> for details. Portability issues: L<perlport/wait>. =item waitpid PID,FLAGS X<waitpid> =for Pod::Functions wait for a particular child process to die Waits for a particular child process to terminate and returns the pid of the deceased process, or C<-1> if there is no such child process. On some systems, a value of 0 indicates that there are processes still running. The status is returned in C<$?> and C<${^CHILD_ERROR_NATIVE}>. If you say use POSIX ":sys_wait_h"; #... do { $kid = waitpid(-1, WNOHANG); } while $kid > 0; then you can do a non-blocking wait for all pending zombie processes. Non-blocking wait is available on machines supporting either the waitpid(2) or wait4(2) syscalls. However, waiting for a particular pid with FLAGS of C<0> is implemented everywhere. (Perl emulates the system call by remembering the status values of processes that have exited but have not been harvested by the Perl script yet.) Note that on some systems, a return value of C<-1> could mean that child processes are being automatically reaped. See L<perlipc> for details, and for other examples. Portability issues: L<perlport/waitpid>. =item wantarray X<wantarray> X<context> =for Pod::Functions get void vs scalar vs list context of current subroutine call Returns true if the context of the currently executing subroutine or C<eval> is looking for a list value. Returns false if the context is looking for a scalar. Returns the undefined value if the context is looking for no value (void context). return unless defined wantarray; # don't bother doing more my @a = complex_calculation(); return wantarray ? @a : "@a"; C<wantarray()>'s result is unspecified in the top level of a file, in a C<BEGIN>, C<UNITCHECK>, C<CHECK>, C<INIT> or C<END> block, or in a C<DESTROY> method. This function should have been named wantlist() instead. =item warn LIST X<warn> X<warning> X<STDERR> =for Pod::Functions print debugging info Prints the value of LIST to STDERR. If the last element of LIST does not end in a newline, it appends the same file/line number text as C<die> does. If the output is empty and C<$@> already contains a value (typically from a previous eval) that value is used after appending C<"\t...caught"> to C<$@>. This is useful for staying almost, but not entirely similar to C<die>. If C<$@> is empty then the string C<"Warning: Something's wrong"> is used. No message is printed if there is a C<$SIG{__WARN__}> handler installed. It is the handler's responsibility to deal with the message as it sees fit (like, for instance, converting it into a C<die>). Most handlers must therefore arrange to actually display the warnings that they are not prepared to deal with, by calling C<warn> again in the handler. Note that this is quite safe and will not produce an endless loop, since C<__WARN__> hooks are not called from inside one. You will find this behavior is slightly different from that of C<$SIG{__DIE__}> handlers (which don't suppress the error text, but can instead call C<die> again to change it). Using a C<__WARN__> handler provides a powerful way to silence all warnings (even the so-called mandatory ones). An example: # wipe out *all* compile-time warnings BEGIN { $SIG{'__WARN__'} = sub { warn $_[0] if $DOWARN } } my $foo = 10; my $foo = 20; # no warning about duplicate my $foo, # but hey, you asked for it! # no compile-time or run-time warnings before here $DOWARN = 1; # run-time warnings enabled after here warn "\$foo is alive and $foo!"; # does show up See L<perlvar> for details on setting C<%SIG> entries and for more examples. See the Carp module for other kinds of warnings using its carp() and cluck() functions. =item write FILEHANDLE X<write> =item write EXPR =item write =for Pod::Functions print a picture record Writes a formatted record (possibly multi-line) to the specified FILEHANDLE, using the format associated with that file. By default the format for a file is the one having the same name as the filehandle, but the format for the current output channel (see the C<select> function) may be set explicitly by assigning the name of the format to the C<$~> variable. Top of form processing is handled automatically: if there is insufficient room on the current page for the formatted record, the page is advanced by writing a form feed, a special top-of-page format is used to format the new page header before the record is written. By default, the top-of-page format is the name of the filehandle with "_TOP" appended. This would be a problem with autovivified filehandles, but it may be dynamically set to the format of your choice by assigning the name to the C<$^> variable while that filehandle is selected. The number of lines remaining on the current page is in variable C<$->, which can be set to C<0> to force a new page. If FILEHANDLE is unspecified, output goes to the current default output channel, which starts out as STDOUT but may be changed by the C<select> operator. If the FILEHANDLE is an EXPR, then the expression is evaluated and the resulting string is used to look up the name of the FILEHANDLE at run time. For more on formats, see L<perlform>. Note that write is I<not> the opposite of C<read>. Unfortunately. =item y/// =for Pod::Functions transliterate a string The transliteration operator. Same as C<tr///>. See L<perlop/"Quote and Quote-like Operators">. =back =head2 Non-function Keywords by Cross-reference =head3 perldata =over =item __DATA__ =item __END__ These keywords are documented in L<perldata/"Special Literals">. =back =head3 perlmod =over =item BEGIN =item CHECK =item END =item INIT =item UNITCHECK These compile phase keywords are documented in L<perlmod/"BEGIN, UNITCHECK, CHECK, INIT and END">. =back =head3 perlobj =over =item DESTROY This method keyword is documented in L<perlobj/"Destructors">. =back =head3 perlop =over =item and =item cmp =item eq =item ge =item gt =item if =item le =item lt =item ne =item not =item or =item x =item xor These operators are documented in L<perlop>. =back =head3 perlsub =over =item AUTOLOAD This keyword is documented in L<perlsub/"Autoloading">. =back =head3 perlsyn =over =item else =item elseif =item elsif =item for =item foreach =item unless =item until =item while These flow-control keywords are documented in L<perlsyn/"Compound Statements">. =back =over =item default =item given =item when These flow-control keywords related to the experimental switch feature are documented in L<perlsyn/"Switch Statements"> . =back =cut
liuyangning/WX_web
xampp/perl/lib/pods/perlfunc.pod
Perl
mit
346,554
=head1 NAME perlvar - Perl predefined variables =head1 DESCRIPTION =head2 Predefined Names The following names have special meaning to Perl. Most punctuation names have reasonable mnemonics, or analogs in the shells. Nevertheless, if you wish to use long variable names, you need only say use English; at the top of your program. This aliases all the short names to the long names in the current package. Some even have medium names, generally borrowed from B<awk>. In general, it's best to use the use English '-no_match_vars'; invocation if you don't need $PREMATCH, $MATCH, or $POSTMATCH, as it avoids a certain performance hit with the use of regular expressions. See L<English>. Variables that depend on the currently selected filehandle may be set by calling an appropriate object method on the IO::Handle object, although this is less efficient than using the regular built-in variables. (Summary lines below for this contain the word HANDLE.) First you must say use IO::Handle; after which you may use either method HANDLE EXPR or more safely, HANDLE->method(EXPR) Each method returns the old value of the IO::Handle attribute. The methods each take an optional EXPR, which, if supplied, specifies the new value for the IO::Handle attribute in question. If not supplied, most methods do nothing to the current value--except for autoflush(), which will assume a 1 for you, just to be different. Because loading in the IO::Handle class is an expensive operation, you should learn how to use the regular built-in variables. A few of these variables are considered "read-only". This means that if you try to assign to this variable, either directly or indirectly through a reference, you'll raise a run-time exception. You should be very careful when modifying the default values of most special variables described in this document. In most cases you want to localize these variables before changing them, since if you don't, the change may affect other modules which rely on the default values of the special variables that you have changed. This is one of the correct ways to read the whole file at once: open my $fh, "<", "foo" or die $!; local $/; # enable localized slurp mode my $content = <$fh>; close $fh; But the following code is quite bad: open my $fh, "<", "foo" or die $!; undef $/; # enable slurp mode my $content = <$fh>; close $fh; since some other module, may want to read data from some file in the default "line mode", so if the code we have just presented has been executed, the global value of C<$/> is now changed for any other code running inside the same Perl interpreter. Usually when a variable is localized you want to make sure that this change affects the shortest scope possible. So unless you are already inside some short C<{}> block, you should create one yourself. For example: my $content = ''; open my $fh, "<", "foo" or die $!; { local $/; $content = <$fh>; } close $fh; Here is an example of how your own code can go broken: for (1..5){ nasty_break(); print "$_ "; } sub nasty_break { $_ = 5; # do something with $_ } You probably expect this code to print: 1 2 3 4 5 but instead you get: 5 5 5 5 5 Why? Because nasty_break() modifies C<$_> without localizing it first. The fix is to add local(): local $_ = 5; It's easy to notice the problem in such a short example, but in more complicated code you are looking for trouble if you don't localize changes to the special variables. The following list is ordered by scalar variables first, then the arrays, then the hashes. =over 8 =item $ARG =item $_ X<$_> X<$ARG> The default input and pattern-searching space. The following pairs are equivalent: while (<>) {...} # equivalent only in while! while (defined($_ = <>)) {...} /^Subject:/ $_ =~ /^Subject:/ tr/a-z/A-Z/ $_ =~ tr/a-z/A-Z/ chomp chomp($_) Here are the places where Perl will assume $_ even if you don't use it: =over 3 =item * The following functions: abs, alarm, chomp, chop, chr, chroot, cos, defined, eval, exp, glob, hex, int, lc, lcfirst, length, log, lstat, mkdir, oct, ord, pos, print, quotemeta, readlink, readpipe, ref, require, reverse (in scalar context only), rmdir, sin, split (on its second argument), sqrt, stat, study, uc, ucfirst, unlink, unpack. =item * All file tests (C<-f>, C<-d>) except for C<-t>, which defaults to STDIN. See L<perlfunc/-X> =item * The pattern matching operations C<m//>, C<s///> and C<tr///> (aka C<y///>) when used without an C<=~> operator. =item * The default iterator variable in a C<foreach> loop if no other variable is supplied. =item * The implicit iterator variable in the grep() and map() functions. =item * The implicit variable of given(). =item * The default place to put an input record when a C<< <FH> >> operation's result is tested by itself as the sole criterion of a C<while> test. Outside a C<while> test, this will not happen. =back As C<$_> is a global variable, this may lead in some cases to unwanted side-effects. As of perl 5.9.1, you can now use a lexical version of C<$_> by declaring it in a file or in a block with C<my>. Moreover, declaring C<our $_> restores the global C<$_> in the current scope. (Mnemonic: underline is understood in certain operations.) =back =over 8 =item $a =item $b X<$a> X<$b> Special package variables when using sort(), see L<perlfunc/sort>. Because of this specialness $a and $b don't need to be declared (using use vars, or our()) even when using the C<strict 'vars'> pragma. Don't lexicalize them with C<my $a> or C<my $b> if you want to be able to use them in the sort() comparison block or function. =back =over 8 =item $<I<digits>> X<$1> X<$2> X<$3> Contains the subpattern from the corresponding set of capturing parentheses from the last pattern match, not counting patterns matched in nested blocks that have been exited already. (Mnemonic: like \digits.) These variables are all read-only and dynamically scoped to the current BLOCK. =item $MATCH =item $& X<$&> X<$MATCH> The string matched by the last successful pattern match (not counting any matches hidden within a BLOCK or eval() enclosed by the current BLOCK). (Mnemonic: like & in some editors.) This variable is read-only and dynamically scoped to the current BLOCK. The use of this variable anywhere in a program imposes a considerable performance penalty on all regular expression matches. See L</BUGS>. See L</@-> for a replacement. =item ${^MATCH} X<${^MATCH}> This is similar to C<$&> (C<$MATCH>) except that it does not incur the performance penalty associated with that variable, and is only guaranteed to return a defined value when the pattern was compiled or executed with the C</p> modifier. =item $PREMATCH =item $` X<$`> X<$PREMATCH> The string preceding whatever was matched by the last successful pattern match (not counting any matches hidden within a BLOCK or eval enclosed by the current BLOCK). (Mnemonic: C<`> often precedes a quoted string.) This variable is read-only. The use of this variable anywhere in a program imposes a considerable performance penalty on all regular expression matches. See L</BUGS>. See L</@-> for a replacement. =item ${^PREMATCH} X<${^PREMATCH}> This is similar to C<$`> ($PREMATCH) except that it does not incur the performance penalty associated with that variable, and is only guaranteed to return a defined value when the pattern was compiled or executed with the C</p> modifier. =item $POSTMATCH =item $' X<$'> X<$POSTMATCH> The string following whatever was matched by the last successful pattern match (not counting any matches hidden within a BLOCK or eval() enclosed by the current BLOCK). (Mnemonic: C<'> often follows a quoted string.) Example: local $_ = 'abcdefghi'; /def/; print "$`:$&:$'\n"; # prints abc:def:ghi This variable is read-only and dynamically scoped to the current BLOCK. The use of this variable anywhere in a program imposes a considerable performance penalty on all regular expression matches. See L</BUGS>. See L</@-> for a replacement. =item ${^POSTMATCH} X<${^POSTMATCH}> This is similar to C<$'> (C<$POSTMATCH>) except that it does not incur the performance penalty associated with that variable, and is only guaranteed to return a defined value when the pattern was compiled or executed with the C</p> modifier. =item $LAST_PAREN_MATCH =item $+ X<$+> X<$LAST_PAREN_MATCH> The text matched by the last bracket of the last successful search pattern. This is useful if you don't know which one of a set of alternative patterns matched. For example: /Version: (.*)|Revision: (.*)/ && ($rev = $+); (Mnemonic: be positive and forward looking.) This variable is read-only and dynamically scoped to the current BLOCK. =item $LAST_SUBMATCH_RESULT =item $^N X<$^N> The text matched by the used group most-recently closed (i.e. the group with the rightmost closing parenthesis) of the last successful search pattern. (Mnemonic: the (possibly) Nested parenthesis that most recently closed.) This is primarily used inside C<(?{...})> blocks for examining text recently matched. For example, to effectively capture text to a variable (in addition to C<$1>, C<$2>, etc.), replace C<(...)> with (?:(...)(?{ $var = $^N })) By setting and then using C<$var> in this way relieves you from having to worry about exactly which numbered set of parentheses they are. This variable is dynamically scoped to the current BLOCK. =item @LAST_MATCH_END =item @+ X<@+> X<@LAST_MATCH_END> This array holds the offsets of the ends of the last successful submatches in the currently active dynamic scope. C<$+[0]> is the offset into the string of the end of the entire match. This is the same value as what the C<pos> function returns when called on the variable that was matched against. The I<n>th element of this array holds the offset of the I<n>th submatch, so C<$+[1]> is the offset past where $1 ends, C<$+[2]> the offset past where $2 ends, and so on. You can use C<$#+> to determine how many subgroups were in the last successful match. See the examples given for the C<@-> variable. =item %LAST_PAREN_MATCH =item %+ X<%+> Similar to C<@+>, the C<%+> hash allows access to the named capture buffers, should they exist, in the last successful match in the currently active dynamic scope. For example, C<$+{foo}> is equivalent to C<$1> after the following match: 'foo' =~ /(?<foo>foo)/; The keys of the C<%+> hash list only the names of buffers that have captured (and that are thus associated to defined values). The underlying behaviour of C<%+> is provided by the L<Tie::Hash::NamedCapture> module. B<Note:> C<%-> and C<%+> are tied views into a common internal hash associated with the last successful regular expression. Therefore mixing iterative access to them via C<each> may have unpredictable results. Likewise, if the last successful match changes, then the results may be surprising. =item HANDLE->input_line_number(EXPR) =item $INPUT_LINE_NUMBER =item $NR =item $. X<$.> X<$NR> X<$INPUT_LINE_NUMBER> X<line number> Current line number for the last filehandle accessed. Each filehandle in Perl counts the number of lines that have been read from it. (Depending on the value of C<$/>, Perl's idea of what constitutes a line may not match yours.) When a line is read from a filehandle (via readline() or C<< <> >>), or when tell() or seek() is called on it, C<$.> becomes an alias to the line counter for that filehandle. You can adjust the counter by assigning to C<$.>, but this will not actually move the seek pointer. I<Localizing C<$.> will not localize the filehandle's line count>. Instead, it will localize perl's notion of which filehandle C<$.> is currently aliased to. C<$.> is reset when the filehandle is closed, but B<not> when an open filehandle is reopened without an intervening close(). For more details, see L<perlop/"IE<sol>O Operators">. Because C<< <> >> never does an explicit close, line numbers increase across ARGV files (but see examples in L<perlfunc/eof>). You can also use C<< HANDLE->input_line_number(EXPR) >> to access the line counter for a given filehandle without having to worry about which handle you last accessed. (Mnemonic: many programs use "." to mean the current line number.) =item IO::Handle->input_record_separator(EXPR) =item $INPUT_RECORD_SEPARATOR =item $RS =item $/ X<$/> X<$RS> X<$INPUT_RECORD_SEPARATOR> The input record separator, newline by default. This influences Perl's idea of what a "line" is. Works like B<awk>'s RS variable, including treating empty lines as a terminator if set to the null string. (An empty line cannot contain any spaces or tabs.) You may set it to a multi-character string to match a multi-character terminator, or to C<undef> to read through the end of file. Setting it to C<"\n\n"> means something slightly different than setting to C<"">, if the file contains consecutive empty lines. Setting to C<""> will treat two or more consecutive empty lines as a single empty line. Setting to C<"\n\n"> will blindly assume that the next input character belongs to the next paragraph, even if it's a newline. (Mnemonic: / delimits line boundaries when quoting poetry.) local $/; # enable "slurp" mode local $_ = <FH>; # whole file now here s/\n[ \t]+/ /g; Remember: the value of C<$/> is a string, not a regex. B<awk> has to be better for something. :-) Setting C<$/> to a reference to an integer, scalar containing an integer, or scalar that's convertible to an integer will attempt to read records instead of lines, with the maximum record size being the referenced integer. So this: local $/ = \32768; # or \"32768", or \$var_containing_32768 open my $fh, "<", $myfile or die $!; local $_ = <$fh>; will read a record of no more than 32768 bytes from FILE. If you're not reading from a record-oriented file (or your OS doesn't have record-oriented files), then you'll likely get a full chunk of data with every read. If a record is larger than the record size you've set, you'll get the record back in pieces. Trying to set the record size to zero or less will cause reading in the (rest of the) whole file. On VMS, record reads are done with the equivalent of C<sysread>, so it's best not to mix record and non-record reads on the same file. (This is unlikely to be a problem, because any file you'd want to read in record mode is probably unusable in line mode.) Non-VMS systems do normal I/O, so it's safe to mix record and non-record reads of a file. See also L<perlport/"Newlines">. Also see C<$.>. =item HANDLE->autoflush(EXPR) =item $OUTPUT_AUTOFLUSH =item $| X<$|> X<autoflush> X<flush> X<$OUTPUT_AUTOFLUSH> If set to nonzero, forces a flush right away and after every write or print on the currently selected output channel. Default is 0 (regardless of whether the channel is really buffered by the system or not; C<$|> tells you only whether you've asked Perl explicitly to flush after each write). STDOUT will typically be line buffered if output is to the terminal and block buffered otherwise. Setting this variable is useful primarily when you are outputting to a pipe or socket, such as when you are running a Perl program under B<rsh> and want to see the output as it's happening. This has no effect on input buffering. See L<perlfunc/getc> for that. See L<perldoc/select> on how to select the output channel. See also L<IO::Handle>. (Mnemonic: when you want your pipes to be piping hot.) =item IO::Handle->output_field_separator EXPR =item $OUTPUT_FIELD_SEPARATOR =item $OFS =item $, X<$,> X<$OFS> X<$OUTPUT_FIELD_SEPARATOR> The output field separator for the print operator. If defined, this value is printed between each of print's arguments. Default is C<undef>. (Mnemonic: what is printed when there is a "," in your print statement.) =item IO::Handle->output_record_separator EXPR =item $OUTPUT_RECORD_SEPARATOR =item $ORS =item $\ X<$\> X<$ORS> X<$OUTPUT_RECORD_SEPARATOR> The output record separator for the print operator. If defined, this value is printed after the last of print's arguments. Default is C<undef>. (Mnemonic: you set C<$\> instead of adding "\n" at the end of the print. Also, it's just like C<$/>, but it's what you get "back" from Perl.) =item $LIST_SEPARATOR =item $" X<$"> X<$LIST_SEPARATOR> This is like C<$,> except that it applies to array and slice values interpolated into a double-quoted string (or similar interpreted string). Default is a space. (Mnemonic: obvious, I think.) =item $SUBSCRIPT_SEPARATOR =item $SUBSEP =item $; X<$;> X<$SUBSEP> X<SUBSCRIPT_SEPARATOR> The subscript separator for multidimensional array emulation. If you refer to a hash element as $foo{$a,$b,$c} it really means $foo{join($;, $a, $b, $c)} But don't put @foo{$a,$b,$c} # a slice--note the @ which means ($foo{$a},$foo{$b},$foo{$c}) Default is "\034", the same as SUBSEP in B<awk>. If your keys contain binary data there might not be any safe value for C<$;>. (Mnemonic: comma (the syntactic subscript separator) is a semi-semicolon. Yeah, I know, it's pretty lame, but C<$,> is already taken for something more important.) Consider using "real" multidimensional arrays as described in L<perllol>. =item HANDLE->format_page_number(EXPR) =item $FORMAT_PAGE_NUMBER =item $% X<$%> X<$FORMAT_PAGE_NUMBER> The current page number of the currently selected output channel. Used with formats. (Mnemonic: % is page number in B<nroff>.) =item HANDLE->format_lines_per_page(EXPR) =item $FORMAT_LINES_PER_PAGE =item $= X<$=> X<$FORMAT_LINES_PER_PAGE> The current page length (printable lines) of the currently selected output channel. Default is 60. Used with formats. (Mnemonic: = has horizontal lines.) =item HANDLE->format_lines_left(EXPR) =item $FORMAT_LINES_LEFT =item $- X<$-> X<$FORMAT_LINES_LEFT> The number of lines left on the page of the currently selected output channel. Used with formats. (Mnemonic: lines_on_page - lines_printed.) =item @LAST_MATCH_START =item @- X<@-> X<@LAST_MATCH_START> $-[0] is the offset of the start of the last successful match. C<$-[>I<n>C<]> is the offset of the start of the substring matched by I<n>-th subpattern, or undef if the subpattern did not match. Thus after a match against $_, $& coincides with C<substr $_, $-[0], $+[0] - $-[0]>. Similarly, $I<n> coincides with C<substr $_, $-[n], $+[n] - $-[n]> if C<$-[n]> is defined, and $+ coincides with C<substr $_, $-[$#-], $+[$#-] - $-[$#-]>. One can use C<$#-> to find the last matched subgroup in the last successful match. Contrast with C<$#+>, the number of subgroups in the regular expression. Compare with C<@+>. This array holds the offsets of the beginnings of the last successful submatches in the currently active dynamic scope. C<$-[0]> is the offset into the string of the beginning of the entire match. The I<n>th element of this array holds the offset of the I<n>th submatch, so C<$-[1]> is the offset where $1 begins, C<$-[2]> the offset where $2 begins, and so on. After a match against some variable $var: =over 5 =item C<$`> is the same as C<substr($var, 0, $-[0])> =item C<$&> is the same as C<substr($var, $-[0], $+[0] - $-[0])> =item C<$'> is the same as C<substr($var, $+[0])> =item C<$1> is the same as C<substr($var, $-[1], $+[1] - $-[1])> =item C<$2> is the same as C<substr($var, $-[2], $+[2] - $-[2])> =item C<$3> is the same as C<substr($var, $-[3], $+[3] - $-[3])> =back =item %- X<%-> Similar to C<%+>, this variable allows access to the named capture buffers in the last successful match in the currently active dynamic scope. To each capture buffer name found in the regular expression, it associates a reference to an array containing the list of values captured by all buffers with that name (should there be several of them), in the order where they appear. Here's an example: if ('1234' =~ /(?<A>1)(?<B>2)(?<A>3)(?<B>4)/) { foreach my $bufname (sort keys %-) { my $ary = $-{$bufname}; foreach my $idx (0..$#$ary) { print "\$-{$bufname}[$idx] : ", (defined($ary->[$idx]) ? "'$ary->[$idx]'" : "undef"), "\n"; } } } would print out: $-{A}[0] : '1' $-{A}[1] : '3' $-{B}[0] : '2' $-{B}[1] : '4' The keys of the C<%-> hash correspond to all buffer names found in the regular expression. The behaviour of C<%-> is implemented via the L<Tie::Hash::NamedCapture> module. B<Note:> C<%-> and C<%+> are tied views into a common internal hash associated with the last successful regular expression. Therefore mixing iterative access to them via C<each> may have unpredictable results. Likewise, if the last successful match changes, then the results may be surprising. =item HANDLE->format_name(EXPR) =item $FORMAT_NAME =item $~ X<$~> X<$FORMAT_NAME> The name of the current report format for the currently selected output channel. Default is the name of the filehandle. (Mnemonic: brother to C<$^>.) =item HANDLE->format_top_name(EXPR) =item $FORMAT_TOP_NAME =item $^ X<$^> X<$FORMAT_TOP_NAME> The name of the current top-of-page format for the currently selected output channel. Default is the name of the filehandle with _TOP appended. (Mnemonic: points to top of page.) =item IO::Handle->format_line_break_characters EXPR =item $FORMAT_LINE_BREAK_CHARACTERS =item $: X<$:> X<FORMAT_LINE_BREAK_CHARACTERS> The current set of characters after which a string may be broken to fill continuation fields (starting with ^) in a format. Default is S<" \n-">, to break on whitespace or hyphens. (Mnemonic: a "colon" in poetry is a part of a line.) =item IO::Handle->format_formfeed EXPR =item $FORMAT_FORMFEED =item $^L X<$^L> X<$FORMAT_FORMFEED> What formats output as a form feed. Default is \f. =item $ACCUMULATOR =item $^A X<$^A> X<$ACCUMULATOR> The current value of the write() accumulator for format() lines. A format contains formline() calls that put their result into C<$^A>. After calling its format, write() prints out the contents of C<$^A> and empties. So you never really see the contents of C<$^A> unless you call formline() yourself and then look at it. See L<perlform> and L<perlfunc/formline()>. =item $CHILD_ERROR =item $? X<$?> X<$CHILD_ERROR> The status returned by the last pipe close, backtick (C<``>) command, successful call to wait() or waitpid(), or from the system() operator. This is just the 16-bit status word returned by the traditional Unix wait() system call (or else is made up to look like it). Thus, the exit value of the subprocess is really (C<<< $? >> 8 >>>), and C<$? & 127> gives which signal, if any, the process died from, and C<$? & 128> reports whether there was a core dump. (Mnemonic: similar to B<sh> and B<ksh>.) Additionally, if the C<h_errno> variable is supported in C, its value is returned via $? if any C<gethost*()> function fails. If you have installed a signal handler for C<SIGCHLD>, the value of C<$?> will usually be wrong outside that handler. Inside an C<END> subroutine C<$?> contains the value that is going to be given to C<exit()>. You can modify C<$?> in an C<END> subroutine to change the exit status of your program. For example: END { $? = 1 if $? == 255; # die would make it 255 } Under VMS, the pragma C<use vmsish 'status'> makes C<$?> reflect the actual VMS exit status, instead of the default emulation of POSIX status; see L<perlvms/$?> for details. Also see L<Error Indicators>. =item ${^CHILD_ERROR_NATIVE} X<$^CHILD_ERROR_NATIVE> The native status returned by the last pipe close, backtick (C<``>) command, successful call to wait() or waitpid(), or from the system() operator. On POSIX-like systems this value can be decoded with the WIFEXITED, WEXITSTATUS, WIFSIGNALED, WTERMSIG, WIFSTOPPED, WSTOPSIG and WIFCONTINUED functions provided by the L<POSIX> module. Under VMS this reflects the actual VMS exit status; i.e. it is the same as $? when the pragma C<use vmsish 'status'> is in effect. =item ${^ENCODING} X<$^ENCODING> The I<object reference> to the Encode object that is used to convert the source code to Unicode. Thanks to this variable your perl script does not have to be written in UTF-8. Default is I<undef>. The direct manipulation of this variable is highly discouraged. =item $OS_ERROR =item $ERRNO =item $! X<$!> X<$ERRNO> X<$OS_ERROR> If used numerically, yields the current value of the C C<errno> variable, or in other words, if a system or library call fails, it sets this variable. This means that the value of C<$!> is meaningful only I<immediately> after a B<failure>: if (open my $fh, "<", $filename) { # Here $! is meaningless. ... } else { # ONLY here is $! meaningful. ... # Already here $! might be meaningless. } # Since here we might have either success or failure, # here $! is meaningless. In the above I<meaningless> stands for anything: zero, non-zero, C<undef>. A successful system or library call does B<not> set the variable to zero. If used as a string, yields the corresponding system error string. You can assign a number to C<$!> to set I<errno> if, for instance, you want C<"$!"> to return the string for error I<n>, or you want to set the exit value for the die() operator. (Mnemonic: What just went bang?) Also see L<Error Indicators>. =item %OS_ERROR =item %ERRNO =item %! X<%!> Each element of C<%!> has a true value only if C<$!> is set to that value. For example, C<$!{ENOENT}> is true if and only if the current value of C<$!> is C<ENOENT>; that is, if the most recent error was "No such file or directory" (or its moral equivalent: not all operating systems give that exact error, and certainly not all languages). To check if a particular key is meaningful on your system, use C<exists $!{the_key}>; for a list of legal keys, use C<keys %!>. See L<Errno> for more information, and also see above for the validity of C<$!>. =item $EXTENDED_OS_ERROR =item $^E X<$^E> X<$EXTENDED_OS_ERROR> Error information specific to the current operating system. At the moment, this differs from C<$!> under only VMS, OS/2, and Win32 (and for MacPerl). On all other platforms, C<$^E> is always just the same as C<$!>. Under VMS, C<$^E> provides the VMS status value from the last system error. This is more specific information about the last system error than that provided by C<$!>. This is particularly important when C<$!> is set to B<EVMSERR>. Under OS/2, C<$^E> is set to the error code of the last call to OS/2 API either via CRT, or directly from perl. Under Win32, C<$^E> always returns the last error information reported by the Win32 call C<GetLastError()> which describes the last error from within the Win32 API. Most Win32-specific code will report errors via C<$^E>. ANSI C and Unix-like calls set C<errno> and so most portable Perl code will report errors via C<$!>. Caveats mentioned in the description of C<$!> generally apply to C<$^E>, also. (Mnemonic: Extra error explanation.) Also see L<Error Indicators>. =item $EVAL_ERROR =item $@ X<$@> X<$EVAL_ERROR> The Perl syntax error message from the last eval() operator. If $@ is the null string, the last eval() parsed and executed correctly (although the operations you invoked may have failed in the normal fashion). (Mnemonic: Where was the syntax error "at"?) Warning messages are not collected in this variable. You can, however, set up a routine to process warnings by setting C<$SIG{__WARN__}> as described below. Also see L<Error Indicators>. =item $PROCESS_ID =item $PID =item $$ X<$$> X<$PID> X<$PROCESS_ID> The process number of the Perl running this script. You should consider this variable read-only, although it will be altered across fork() calls. (Mnemonic: same as shells.) Note for Linux users: on Linux, the C functions C<getpid()> and C<getppid()> return different values from different threads. In order to be portable, this behavior is not reflected by C<$$>, whose value remains consistent across threads. If you want to call the underlying C<getpid()>, you may use the CPAN module C<Linux::Pid>. =item $REAL_USER_ID =item $UID =item $< X<< $< >> X<$UID> X<$REAL_USER_ID> The real uid of this process. (Mnemonic: it's the uid you came I<from>, if you're running setuid.) You can change both the real uid and the effective uid at the same time by using POSIX::setuid(). Since changes to $< require a system call, check $! after a change attempt to detect any possible errors. =item $EFFECTIVE_USER_ID =item $EUID =item $> X<< $> >> X<$EUID> X<$EFFECTIVE_USER_ID> The effective uid of this process. Example: $< = $>; # set real to effective uid ($<,$>) = ($>,$<); # swap real and effective uid You can change both the effective uid and the real uid at the same time by using POSIX::setuid(). Changes to $> require a check to $! to detect any possible errors after an attempted change. (Mnemonic: it's the uid you went I<to>, if you're running setuid.) C<< $< >> and C<< $> >> can be swapped only on machines supporting setreuid(). =item $REAL_GROUP_ID =item $GID =item $( X<$(> X<$GID> X<$REAL_GROUP_ID> The real gid of this process. If you are on a machine that supports membership in multiple groups simultaneously, gives a space separated list of groups you are in. The first number is the one returned by getgid(), and the subsequent ones by getgroups(), one of which may be the same as the first number. However, a value assigned to C<$(> must be a single number used to set the real gid. So the value given by C<$(> should I<not> be assigned back to C<$(> without being forced numeric, such as by adding zero. Note that this is different to the effective gid (C<$)>) which does take a list. You can change both the real gid and the effective gid at the same time by using POSIX::setgid(). Changes to $( require a check to $! to detect any possible errors after an attempted change. (Mnemonic: parentheses are used to I<group> things. The real gid is the group you I<left>, if you're running setgid.) =item $EFFECTIVE_GROUP_ID =item $EGID =item $) X<$)> X<$EGID> X<$EFFECTIVE_GROUP_ID> The effective gid of this process. If you are on a machine that supports membership in multiple groups simultaneously, gives a space separated list of groups you are in. The first number is the one returned by getegid(), and the subsequent ones by getgroups(), one of which may be the same as the first number. Similarly, a value assigned to C<$)> must also be a space-separated list of numbers. The first number sets the effective gid, and the rest (if any) are passed to setgroups(). To get the effect of an empty list for setgroups(), just repeat the new effective gid; that is, to force an effective gid of 5 and an effectively empty setgroups() list, say C< $) = "5 5" >. You can change both the effective gid and the real gid at the same time by using POSIX::setgid() (use only a single numeric argument). Changes to $) require a check to $! to detect any possible errors after an attempted change. (Mnemonic: parentheses are used to I<group> things. The effective gid is the group that's I<right> for you, if you're running setgid.) C<< $< >>, C<< $> >>, C<$(> and C<$)> can be set only on machines that support the corresponding I<set[re][ug]id()> routine. C<$(> and C<$)> can be swapped only on machines supporting setregid(). =item $PROGRAM_NAME =item $0 X<$0> X<$PROGRAM_NAME> Contains the name of the program being executed. On some (read: not all) operating systems assigning to C<$0> modifies the argument area that the C<ps> program sees. On some platforms you may have to use special C<ps> options or a different C<ps> to see the changes. Modifying the $0 is more useful as a way of indicating the current program state than it is for hiding the program you're running. (Mnemonic: same as B<sh> and B<ksh>.) Note that there are platform specific limitations on the maximum length of C<$0>. In the most extreme case it may be limited to the space occupied by the original C<$0>. In some platforms there may be arbitrary amount of padding, for example space characters, after the modified name as shown by C<ps>. In some platforms this padding may extend all the way to the original length of the argument area, no matter what you do (this is the case for example with Linux 2.2). Note for BSD users: setting C<$0> does not completely remove "perl" from the ps(1) output. For example, setting C<$0> to C<"foobar"> may result in C<"perl: foobar (perl)"> (whether both the C<"perl: "> prefix and the " (perl)" suffix are shown depends on your exact BSD variant and version). This is an operating system feature, Perl cannot help it. In multithreaded scripts Perl coordinates the threads so that any thread may modify its copy of the C<$0> and the change becomes visible to ps(1) (assuming the operating system plays along). Note that the view of C<$0> the other threads have will not change since they have their own copies of it. If the program has been given to perl via the switches C<-e> or C<-E>, C<$0> will contain the string C<"-e">. =item $[ X<$[> The index of the first element in an array, and of the first character in a substring. Default is 0, but you could theoretically set it to 1 to make Perl behave more like B<awk> (or Fortran) when subscripting and when evaluating the index() and substr() functions. (Mnemonic: [ begins subscripts.) As of release 5 of Perl, assignment to C<$[> is treated as a compiler directive, and cannot influence the behavior of any other file. (That's why you can only assign compile-time constants to it.) Its use is deprecated, and will trigger a warning (if the deprecation L<warnings> category is enabled. You did C<use warnings>, right?) Note that, unlike other compile-time directives (such as L<strict>), assignment to C<$[> can be seen from outer lexical scopes in the same file. However, you can use local() on it to strictly bind its value to a lexical block. =item $] X<$]> The version + patchlevel / 1000 of the Perl interpreter. This variable can be used to determine whether the Perl interpreter executing a script is in the right range of versions. (Mnemonic: Is this version of perl in the right bracket?) Example: warn "No checksumming!\n" if $] < 3.019; See also the documentation of C<use VERSION> and C<require VERSION> for a convenient way to fail if the running Perl interpreter is too old. The floating point representation can sometimes lead to inaccurate numeric comparisons. See C<$^V> for a more modern representation of the Perl version that allows accurate string comparisons. =item $COMPILING =item $^C X<$^C> X<$COMPILING> The current value of the flag associated with the B<-c> switch. Mainly of use with B<-MO=...> to allow code to alter its behavior when being compiled, such as for example to AUTOLOAD at compile time rather than normal, deferred loading. Setting C<$^C = 1> is similar to calling C<B::minus_c>. =item $DEBUGGING =item $^D X<$^D> X<$DEBUGGING> The current value of the debugging flags. (Mnemonic: value of B<-D> switch.) May be read or set. Like its command-line equivalent, you can use numeric or symbolic values, eg C<$^D = 10> or C<$^D = "st">. =item ${^RE_DEBUG_FLAGS} The current value of the regex debugging flags. Set to 0 for no debug output even when the re 'debug' module is loaded. See L<re> for details. =item ${^RE_TRIE_MAXBUF} Controls how certain regex optimisations are applied and how much memory they utilize. This value by default is 65536 which corresponds to a 512kB temporary cache. Set this to a higher value to trade memory for speed when matching large alternations. Set it to a lower value if you want the optimisations to be as conservative of memory as possible but still occur, and set it to a negative value to prevent the optimisation and conserve the most memory. Under normal situations this variable should be of no interest to you. =item $SYSTEM_FD_MAX =item $^F X<$^F> X<$SYSTEM_FD_MAX> The maximum system file descriptor, ordinarily 2. System file descriptors are passed to exec()ed processes, while higher file descriptors are not. Also, during an open(), system file descriptors are preserved even if the open() fails. (Ordinary file descriptors are closed before the open() is attempted.) The close-on-exec status of a file descriptor will be decided according to the value of C<$^F> when the corresponding file, pipe, or socket was opened, not the time of the exec(). =item $^H WARNING: This variable is strictly for internal use only. Its availability, behavior, and contents are subject to change without notice. This variable contains compile-time hints for the Perl interpreter. At the end of compilation of a BLOCK the value of this variable is restored to the value when the interpreter started to compile the BLOCK. When perl begins to parse any block construct that provides a lexical scope (e.g., eval body, required file, subroutine body, loop body, or conditional block), the existing value of $^H is saved, but its value is left unchanged. When the compilation of the block is completed, it regains the saved value. Between the points where its value is saved and restored, code that executes within BEGIN blocks is free to change the value of $^H. This behavior provides the semantic of lexical scoping, and is used in, for instance, the C<use strict> pragma. The contents should be an integer; different bits of it are used for different pragmatic flags. Here's an example: sub add_100 { $^H |= 0x100 } sub foo { BEGIN { add_100() } bar->baz($boon); } Consider what happens during execution of the BEGIN block. At this point the BEGIN block has already been compiled, but the body of foo() is still being compiled. The new value of $^H will therefore be visible only while the body of foo() is being compiled. Substitution of the above BEGIN block with: BEGIN { require strict; strict->import('vars') } demonstrates how C<use strict 'vars'> is implemented. Here's a conditional version of the same lexical pragma: BEGIN { require strict; strict->import('vars') if $condition } =item %^H The %^H hash provides the same scoping semantic as $^H. This makes it useful for implementation of lexically scoped pragmas. See L<perlpragma>. =item $INPLACE_EDIT =item $^I X<$^I> X<$INPLACE_EDIT> The current value of the inplace-edit extension. Use C<undef> to disable inplace editing. (Mnemonic: value of B<-i> switch.) =item $^M X<$^M> By default, running out of memory is an untrappable, fatal error. However, if suitably built, Perl can use the contents of C<$^M> as an emergency memory pool after die()ing. Suppose that your Perl were compiled with C<-DPERL_EMERGENCY_SBRK> and used Perl's malloc. Then $^M = 'a' x (1 << 16); would allocate a 64K buffer for use in an emergency. See the F<INSTALL> file in the Perl distribution for information on how to add custom C compilation flags when compiling perl. To discourage casual use of this advanced feature, there is no L<English|English> long name for this variable. =item $OSNAME =item $^O X<$^O> X<$OSNAME> The name of the operating system under which this copy of Perl was built, as determined during the configuration process. The value is identical to C<$Config{'osname'}>. See also L<Config> and the B<-V> command-line switch documented in L<perlrun>. In Windows platforms, $^O is not very helpful: since it is always C<MSWin32>, it doesn't tell the difference between 95/98/ME/NT/2000/XP/CE/.NET. Use Win32::GetOSName() or Win32::GetOSVersion() (see L<Win32> and L<perlport>) to distinguish between the variants. =item ${^OPEN} An internal variable used by PerlIO. A string in two parts, separated by a C<\0> byte, the first part describes the input layers, the second part describes the output layers. =item $PERLDB =item $^P X<$^P> X<$PERLDB> The internal variable for debugging support. The meanings of the various bits are subject to change, but currently indicate: =over 6 =item 0x01 Debug subroutine enter/exit. =item 0x02 Line-by-line debugging. Causes DB::DB() subroutine to be called for each statement executed. Also causes saving source code lines (like 0x400). =item 0x04 Switch off optimizations. =item 0x08 Preserve more data for future interactive inspections. =item 0x10 Keep info about source lines on which a subroutine is defined. =item 0x20 Start with single-step on. =item 0x40 Use subroutine address instead of name when reporting. =item 0x80 Report C<goto &subroutine> as well. =item 0x100 Provide informative "file" names for evals based on the place they were compiled. =item 0x200 Provide informative names to anonymous subroutines based on the place they were compiled. =item 0x400 Save source code lines into C<@{"_<$filename"}>. =back Some bits may be relevant at compile-time only, some at run-time only. This is a new mechanism and the details may change. See also L<perldebguts>. =item $LAST_REGEXP_CODE_RESULT =item $^R X<$^R> X<$LAST_REGEXP_CODE_RESULT> The result of evaluation of the last successful C<(?{ code })> regular expression assertion (see L<perlre>). May be written to. =item $EXCEPTIONS_BEING_CAUGHT =item $^S X<$^S> X<$EXCEPTIONS_BEING_CAUGHT> Current state of the interpreter. $^S State --------- ------------------- undef Parsing module/eval true (1) Executing an eval false (0) Otherwise The first state may happen in $SIG{__DIE__} and $SIG{__WARN__} handlers. =item $BASETIME =item $^T X<$^T> X<$BASETIME> The time at which the program began running, in seconds since the epoch (beginning of 1970). The values returned by the B<-M>, B<-A>, and B<-C> filetests are based on this value. =item ${^TAINT} Reflects if taint mode is on or off. 1 for on (the program was run with B<-T>), 0 for off, -1 when only taint warnings are enabled (i.e. with B<-t> or B<-TU>). This variable is read-only. =item ${^UNICODE} Reflects certain Unicode settings of Perl. See L<perlrun> documentation for the C<-C> switch for more information about the possible values. This variable is set during Perl startup and is thereafter read-only. =item ${^UTF8CACHE} This variable controls the state of the internal UTF-8 offset caching code. 1 for on (the default), 0 for off, -1 to debug the caching code by checking all its results against linear scans, and panicking on any discrepancy. =item ${^UTF8LOCALE} This variable indicates whether an UTF-8 locale was detected by perl at startup. This information is used by perl when it's in adjust-utf8ness-to-locale mode (as when run with the C<-CL> command-line switch); see L<perlrun> for more info on this. =item $PERL_VERSION =item $^V X<$^V> X<$PERL_VERSION> The revision, version, and subversion of the Perl interpreter, represented as a C<version> object. This variable first appeared in perl 5.6.0; earlier versions of perl will see an undefined value. Before perl 5.10.0 $^V was represented as a v-string. $^V can be used to determine whether the Perl interpreter executing a script is in the right range of versions. (Mnemonic: use ^V for Version Control.) Example: warn "Hashes not randomized!\n" if !$^V or $^V lt v5.8.1 To convert C<$^V> into its string representation use sprintf()'s C<"%vd"> conversion: printf "version is v%vd\n", $^V; # Perl's version See the documentation of C<use VERSION> and C<require VERSION> for a convenient way to fail if the running Perl interpreter is too old. See also C<$]> for an older representation of the Perl version. =item $WARNING =item $^W X<$^W> X<$WARNING> The current value of the warning switch, initially true if B<-w> was used, false otherwise, but directly modifiable. (Mnemonic: related to the B<-w> switch.) See also L<warnings>. =item ${^WARNING_BITS} The current set of warning checks enabled by the C<use warnings> pragma. See the documentation of C<warnings> for more details. =item ${^WIN32_SLOPPY_STAT} If this variable is set to a true value, then stat() on Windows will not try to open the file. This means that the link count cannot be determined and file attributes may be out of date if additional hardlinks to the file exist. On the other hand, not opening the file is considerably faster, especially for files on network drives. This variable could be set in the F<sitecustomize.pl> file to configure the local Perl installation to use "sloppy" stat() by default. See L<perlrun> for more information about site customization. =item $EXECUTABLE_NAME =item $^X X<$^X> X<$EXECUTABLE_NAME> The name used to execute the current copy of Perl, from C's C<argv[0]> or (where supported) F</proc/self/exe>. Depending on the host operating system, the value of $^X may be a relative or absolute pathname of the perl program file, or may be the string used to invoke perl but not the pathname of the perl program file. Also, most operating systems permit invoking programs that are not in the PATH environment variable, so there is no guarantee that the value of $^X is in PATH. For VMS, the value may or may not include a version number. You usually can use the value of $^X to re-invoke an independent copy of the same perl that is currently running, e.g., @first_run = `$^X -le "print int rand 100 for 1..100"`; But recall that not all operating systems support forking or capturing of the output of commands, so this complex statement may not be portable. It is not safe to use the value of $^X as a path name of a file, as some operating systems that have a mandatory suffix on executable files do not require use of the suffix when invoking a command. To convert the value of $^X to a path name, use the following statements: # Build up a set of file names (not command names). use Config; $this_perl = $^X; if ($^O ne 'VMS') {$this_perl .= $Config{_exe} unless $this_perl =~ m/$Config{_exe}$/i;} Because many operating systems permit anyone with read access to the Perl program file to make a copy of it, patch the copy, and then execute the copy, the security-conscious Perl programmer should take care to invoke the installed copy of perl, not the copy referenced by $^X. The following statements accomplish this goal, and produce a pathname that can be invoked as a command or referenced as a file. use Config; $secure_perl_path = $Config{perlpath}; if ($^O ne 'VMS') {$secure_perl_path .= $Config{_exe} unless $secure_perl_path =~ m/$Config{_exe}$/i;} =item ARGV X<ARGV> The special filehandle that iterates over command-line filenames in C<@ARGV>. Usually written as the null filehandle in the angle operator C<< <> >>. Note that currently C<ARGV> only has its magical effect within the C<< <> >> operator; elsewhere it is just a plain filehandle corresponding to the last file opened by C<< <> >>. In particular, passing C<\*ARGV> as a parameter to a function that expects a filehandle may not cause your function to automatically read the contents of all the files in C<@ARGV>. =item $ARGV X<$ARGV> contains the name of the current file when reading from <>. =item @ARGV X<@ARGV> The array @ARGV contains the command-line arguments intended for the script. C<$#ARGV> is generally the number of arguments minus one, because C<$ARGV[0]> is the first argument, I<not> the program's command name itself. See C<$0> for the command name. =item ARGVOUT X<ARGVOUT> The special filehandle that points to the currently open output file when doing edit-in-place processing with B<-i>. Useful when you have to do a lot of inserting and don't want to keep modifying $_. See L<perlrun> for the B<-i> switch. =item @F X<@F> The array @F contains the fields of each line read in when autosplit mode is turned on. See L<perlrun> for the B<-a> switch. This array is package-specific, and must be declared or given a full package name if not in package main when running under C<strict 'vars'>. =item @INC X<@INC> The array @INC contains the list of places that the C<do EXPR>, C<require>, or C<use> constructs look for their library files. It initially consists of the arguments to any B<-I> command-line switches, followed by the default Perl library, probably F</usr/local/lib/perl>, followed by ".", to represent the current directory. ("." will not be appended if taint checks are enabled, either by C<-T> or by C<-t>.) If you need to modify this at runtime, you should use the C<use lib> pragma to get the machine-dependent library properly loaded also: use lib '/mypath/libdir/'; use SomeMod; You can also insert hooks into the file inclusion system by putting Perl code directly into @INC. Those hooks may be subroutine references, array references or blessed objects. See L<perlfunc/require> for details. =item @ARG =item @_ X<@_> X<@ARG> Within a subroutine the array @_ contains the parameters passed to that subroutine. See L<perlsub>. =item %INC X<%INC> The hash %INC contains entries for each filename included via the C<do>, C<require>, or C<use> operators. The key is the filename you specified (with module names converted to pathnames), and the value is the location of the file found. The C<require> operator uses this hash to determine whether a particular file has already been included. If the file was loaded via a hook (e.g. a subroutine reference, see L<perlfunc/require> for a description of these hooks), this hook is by default inserted into %INC in place of a filename. Note, however, that the hook may have set the %INC entry by itself to provide some more specific info. =item %ENV =item $ENV{expr} X<%ENV> The hash %ENV contains your current environment. Setting a value in C<ENV> changes the environment for any child processes you subsequently fork() off. =item %SIG =item $SIG{expr} X<%SIG> The hash C<%SIG> contains signal handlers for signals. For example: sub handler { # 1st argument is signal name my($sig) = @_; print "Caught a SIG$sig--shutting down\n"; close(LOG); exit(0); } $SIG{'INT'} = \&handler; $SIG{'QUIT'} = \&handler; ... $SIG{'INT'} = 'DEFAULT'; # restore default action $SIG{'QUIT'} = 'IGNORE'; # ignore SIGQUIT Using a value of C<'IGNORE'> usually has the effect of ignoring the signal, except for the C<CHLD> signal. See L<perlipc> for more about this special case. Here are some other examples: $SIG{"PIPE"} = "Plumber"; # assumes main::Plumber (not recommended) $SIG{"PIPE"} = \&Plumber; # just fine; assume current Plumber $SIG{"PIPE"} = *Plumber; # somewhat esoteric $SIG{"PIPE"} = Plumber(); # oops, what did Plumber() return?? Be sure not to use a bareword as the name of a signal handler, lest you inadvertently call it. If your system has the sigaction() function then signal handlers are installed using it. This means you get reliable signal handling. The default delivery policy of signals changed in Perl 5.8.0 from immediate (also known as "unsafe") to deferred, also known as "safe signals". See L<perlipc> for more information. Certain internal hooks can be also set using the %SIG hash. The routine indicated by C<$SIG{__WARN__}> is called when a warning message is about to be printed. The warning message is passed as the first argument. The presence of a C<__WARN__> hook causes the ordinary printing of warnings to C<STDERR> to be suppressed. You can use this to save warnings in a variable, or turn warnings into fatal errors, like this: local $SIG{__WARN__} = sub { die $_[0] }; eval $proggie; As the C<'IGNORE'> hook is not supported by C<__WARN__>, you can disable warnings using the empty subroutine: local $SIG{__WARN__} = sub {}; The routine indicated by C<$SIG{__DIE__}> is called when a fatal exception is about to be thrown. The error message is passed as the first argument. When a C<__DIE__> hook routine returns, the exception processing continues as it would have in the absence of the hook, unless the hook routine itself exits via a C<goto>, a loop exit, or a C<die()>. The C<__DIE__> handler is explicitly disabled during the call, so that you can die from a C<__DIE__> handler. Similarly for C<__WARN__>. Due to an implementation glitch, the C<$SIG{__DIE__}> hook is called even inside an eval(). Do not use this to rewrite a pending exception in C<$@>, or as a bizarre substitute for overriding C<CORE::GLOBAL::die()>. This strange action at a distance may be fixed in a future release so that C<$SIG{__DIE__}> is only called if your program is about to exit, as was the original intent. Any other use is deprecated. C<__DIE__>/C<__WARN__> handlers are very special in one respect: they may be called to report (probable) errors found by the parser. In such a case the parser may be in inconsistent state, so any attempt to evaluate Perl code from such a handler will probably result in a segfault. This means that warnings or errors that result from parsing Perl should be used with extreme caution, like this: require Carp if defined $^S; Carp::confess("Something wrong") if defined &Carp::confess; die "Something wrong, but could not load Carp to give backtrace... To see backtrace try starting Perl with -MCarp switch"; Here the first line will load Carp I<unless> it is the parser who called the handler. The second line will print backtrace and die if Carp was available. The third line will be executed only if Carp was not available. See L<perlfunc/die>, L<perlfunc/warn>, L<perlfunc/eval>, and L<warnings> for additional information. =back =head2 Error Indicators X<error> X<exception> The variables C<$@>, C<$!>, C<$^E>, and C<$?> contain information about different types of error conditions that may appear during execution of a Perl program. The variables are shown ordered by the "distance" between the subsystem which reported the error and the Perl process. They correspond to errors detected by the Perl interpreter, C library, operating system, or an external program, respectively. To illustrate the differences between these variables, consider the following Perl expression, which uses a single-quoted string: eval q{ open my $pipe, "/cdrom/install |" or die $!; my @res = <$pipe>; close $pipe or die "bad pipe: $?, $!"; }; After execution of this statement all 4 variables may have been set. C<$@> is set if the string to be C<eval>-ed did not compile (this may happen if C<open> or C<close> were imported with bad prototypes), or if Perl code executed during evaluation die()d . In these cases the value of $@ is the compile error, or the argument to C<die> (which will interpolate C<$!> and C<$?>). (See also L<Fatal>, though.) When the eval() expression above is executed, open(), C<< <PIPE> >>, and C<close> are translated to calls in the C run-time library and thence to the operating system kernel. C<$!> is set to the C library's C<errno> if one of these calls fails. Under a few operating systems, C<$^E> may contain a more verbose error indicator, such as in this case, "CDROM tray not closed." Systems that do not support extended error messages leave C<$^E> the same as C<$!>. Finally, C<$?> may be set to non-0 value if the external program F</cdrom/install> fails. The upper eight bits reflect specific error conditions encountered by the program (the program's exit() value). The lower eight bits reflect mode of failure, like signal death and core dump information See wait(2) for details. In contrast to C<$!> and C<$^E>, which are set only if error condition is detected, the variable C<$?> is set on each C<wait> or pipe C<close>, overwriting the old value. This is more like C<$@>, which on every eval() is always set on failure and cleared on success. For more details, see the individual descriptions at C<$@>, C<$!>, C<$^E>, and C<$?>. =head2 Technical Note on the Syntax of Variable Names Variable names in Perl can have several formats. Usually, they must begin with a letter or underscore, in which case they can be arbitrarily long (up to an internal limit of 251 characters) and may contain letters, digits, underscores, or the special sequence C<::> or C<'>. In this case, the part before the last C<::> or C<'> is taken to be a I<package qualifier>; see L<perlmod>. Perl variable names may also be a sequence of digits or a single punctuation or control character. These names are all reserved for special uses by Perl; for example, the all-digits names are used to hold data captured by backreferences after a regular expression match. Perl has a special syntax for the single-control-character names: It understands C<^X> (caret C<X>) to mean the control-C<X> character. For example, the notation C<$^W> (dollar-sign caret C<W>) is the scalar variable whose name is the single character control-C<W>. This is better than typing a literal control-C<W> into your program. Finally, new in Perl 5.6, Perl variable names may be alphanumeric strings that begin with control characters (or better yet, a caret). These variables must be written in the form C<${^Foo}>; the braces are not optional. C<${^Foo}> denotes the scalar variable whose name is a control-C<F> followed by two C<o>'s. These variables are reserved for future special uses by Perl, except for the ones that begin with C<^_> (control-underscore or caret-underscore). No control-character name that begins with C<^_> will acquire a special meaning in any future version of Perl; such names may therefore be used safely in programs. C<$^_> itself, however, I<is> reserved. Perl identifiers that begin with digits, control characters, or punctuation characters are exempt from the effects of the C<package> declaration and are always forced to be in package C<main>; they are also exempt from C<strict 'vars'> errors. A few other names are also exempt in these ways: ENV STDIN INC STDOUT ARGV STDERR ARGVOUT _ SIG In particular, the new special C<${^_XYZ}> variables are always taken to be in package C<main>, regardless of any C<package> declarations presently in scope. =head1 BUGS Due to an unfortunate accident of Perl's implementation, C<use English> imposes a considerable performance penalty on all regular expression matches in a program, regardless of whether they occur in the scope of C<use English>. For that reason, saying C<use English> in libraries is strongly discouraged. See the Devel::SawAmpersand module documentation from CPAN ( http://www.cpan.org/modules/by-module/Devel/ ) for more information. Writing C<use English '-no_match_vars';> avoids the performance penalty. Having to even think about the C<$^S> variable in your exception handlers is simply wrong. C<$SIG{__DIE__}> as currently implemented invites grievous and difficult to track down errors. Avoid it and use an C<END{}> or CORE::GLOBAL::die override instead.
olapaola/olapaola-android-scripting
perl/src/pod/perlvar.pod
Perl
apache-2.0
59,234
#!/usr/bin/perl use strict; use warnings; use Getopt::Std; use Config::Tiny; use DBI; my (%opt, $library, $gff, $conf, $species, %reads); getopts('g:l:c:s:h', \%opt); var_check(); # Get configuration settings my $Conf = Config::Tiny->read($conf); my $sam = $Conf->{'PIPELINE'}->{'sam'}; my $config = $Conf->{$species}; my $refdb = $config->{'refseq'}; my $source = $config->{'source'}; my $type = $config->{'type'}; my $mol = $type; $mol =~ s/_/ /g; if (!$refdb || !$source || !$type) { print STDERR " No reference database, source or type information found in $conf.\n"; print STDERR " Please add refseq, source and type fields before running this program.\n\n"; exit 1; } # Connect to the SQLite database my $dbh = DBI->connect("dbi:SQLite:dbname=$config->{'db'}","",""); open (GFF, ">$gff") or die " Cannot open $gff: $!\n\n"; print GFF "##gff-version 3\n\n"; print GFF "##Reference sequence database=$refdb\n"; print GFF "##COLUMN1=<Name=seqid,Type=String,Description=\"An identifier for the reference sequence landmark.\">\n"; print GFF "##COLUMN2=<Name=source,Type=String,Description=\"Source sample/tissue.\">\n"; print GFF "##COLUMN3=<Name=type,Type=String,Description=\"Sample type/fraction.\">\n"; print GFF "##COLUMN4=<Name=start,Type=Integer,Description=\"The start of the feature, in 1-based integer coordinates, relative to the landmark given in COLUMN1. Start is always less than end.\">\n"; print GFF "##COLUMN5=<Name=start,Type=Integer,Description=\"The end of the feature, in 1-based integer coordinates, relative to the landmark given in COLUMN1.\">\n"; print GFF "##COLUMN6=<Name=score,Type=Integer,Description=\"Read frequency, the number of times the feature was observed in the given library.\">\n"; print GFF "##COLUMN7=<Name=strand,Type=String,Description=\"Strand, relative to the landmark given in COLUMN1. Positive '+' or minus '-'.\">\n"; print GFF "##COLUMN8=<Name=phase,Type=String,Description=\"No phase given, indicated with a '.'.\">\n"; print GFF "##COLUMN9=<Name=attributes,Type=String,Description=\"List of tag-value pairs separated by ';'.\">\n"; print GFF "##ATTRIBUTE: Name=<Type=Integer,Description=\"An integer assigned to each unique sequence within the given sample.\">\n"; print GFF "##ATTRIBUTE: Seq=<Type=String,Description=\"The nucleotide sequence (5'->3') of the $mol.\">\n"; my $sth = $dbh->prepare("SELECT * FROM `reads` NATURAL JOIN `sequences` WHERE `library_id` = $library"); $sth->execute(); while (my $row = $sth->fetchrow_hashref) { $reads{$row->{'sid'}}->{'reads'} = $row->{'reads'}; $reads{$row->{'sid'}}->{'seq'} = $row->{'seq'}; } open SAM, "$sam view $config->{'bam'} |"; while (my $hit = <SAM>) { my @fields = split /\t/, $hit; my $sid = $fields[0]; my $strand = $fields[1]; my $chrom = $fields[2]; my $start = $fields[3]; my $seq = $fields[9]; next if (!exists($reads{$sid})); # Convert strand bitwise operator to + or - strand $strand = ($strand == 0) ? '+' : '-'; # Use length of sequence to determine end position my $end = $start + length($seq) - 1; my $score = $reads{$sid}->{'reads'}; my $phase = '.'; my $attributes = 'Name='.$sid.';Seq='.$reads{$sid}->{'seq'}; print GFF $chrom."\t"; print GFF $source."\t"; print GFF $type."\t"; print GFF $start."\t"; print GFF $end."\t"; print GFF $score."\t"; print GFF $strand."\t"; print GFF $phase."\t"; print GFF $attributes."\n"; } close SAM; close GFF; exit; sub var_check { if ($opt{'h'}) { var_error(); } if ($opt{'l'}) { $library = $opt{'l'}; } else { var_error(); } if ($opt{'g'}) { $gff = $opt{'g'}; } else { var_error(); } if ($opt{'c'}) { $conf = $opt{'c'}; } else { var_error(); } if ($opt{'s'}) { $species = $opt{'s'}; } else { var_error(); } } sub var_error { print STDERR " This script will output a library to GFF3 for GEO submissions.\n\n"; print STDERR " Usage: library2geo.pl -l <Library ID> -g <GFF output file> -c <conf file> -s <species>\n\n"; print STDERR " -l Library ID.\n\n"; print STDERR " -g GFF3 output file.\n\n"; print STDERR " -c Configuration file.\n\n"; print STDERR " -s Species.\n\n"; print STDERR " -h Print this menu.\n\n"; exit 1; }
nfahlgren/srtools
toolkit/library2geo.pl
Perl
mit
4,263
#!/usr/bin/perl $usage = qq{ hashLookup_tsv.pl <file1> <file2> <field1> <field2a> <field2b> <file1> table or list of IDs to look up (.tsv) <file2> lookup table with two or more fields (.tsv) <field1> field of file1 to match (eg 0) <field2a> field of file2 that matches file1 field <field2b> field of file2 that should be output Goes through each line of file1, and for each field1, finds the matching value in field2a of file2, then prints both the full line of file1 and the looked up value field2b. Files must be tab-delimited. Count fields from 0. }; die "$usage" unless @ARGV == 5; $file1 = $ARGV[0]; $file2 = $ARGV[1]; $field1 = $ARGV[2]; $field2a = $ARGV[3]; $field2b = $ARGV[4]; open (FILE, $file1) or die "Cannot open $file1!"; @data1 = <FILE>; close FILE; open (FILE, $file2) or die "Cannot open $file2!"; @data2 = <FILE>; close FILE; foreach $line (@data2) { chomp $line; @fields2 = split(/\t/, $line); $hash{$fields2[$field2a]} = $fields2[$field2b]; } foreach $line (@data1) { chomp $line; @fields1 = split(/\t/, $line); # print "$fields1[$field1]\t$hash{$fields1[$field1]}\n"; #prints only one field from file1 print "$line\t$hash{$fields1[$field1]}\n"; #prints all fields from file1 } exit;
cuttlefishh/papers
vibrio-fischeri-transcriptomics/code/perl/hashLookup_tsv.pl
Perl
mit
1,324
#!/usr/bin/perl # nv08info.pl use warnings; use strict; # # The MIT License (MIT) # # Copyright (c) 2015 R. Bruce Warrington, Michael J. Wouters # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # Modification history: # 2017-02-27 MJW First version # 2017-12-11 MJW Configurable path for UUCP lock files. Version change to 1.0.1 # use Time::HiRes qw(gettimeofday); use POSIX; use TFLibrary; use vars qw($tmask $opt_c $opt_d $opt_h $opt_r $opt_v); use Switch; use Getopt::Std; use NV08C::DecodeMsg; # declare variables - required because of 'use strict' my($home,$configPath,$logPath,$lockFile,$port,$uucpLockPath,$VERSION,$rx,$rxStatus); my($now,$mjd,$next,$then,$input,$save,$data,$killed,$tstart,$receiverTimeout); my($lastMsg,$msg,$rxmask,$nfound,$first,$msgID,$ret,$nowstr,$sats); my(%Init); my($AUTHORS,$configFile,@info,@required); $AUTHORS = "Louis Marais,Michael Wouters"; $VERSION = "1.0.1"; $0=~s#.*/##; $home=$ENV{HOME}; $configFile="$home/etc/gpscv.conf"; if( !(getopts('c:dhrv')) || ($#ARGV>=1) || $opt_h) { ShowHelp(); exit; } if ($opt_v){ print "$0 version $VERSION\n"; print "Written by $AUTHORS\n"; exit; } if (!(-d "$home/etc")){ ErrorExit("No ~/etc directory found!\n"); } if (-d "$home/logs"){ $logPath="$home/logs"; } else{ ErrorExit("No ~/logs directory found!\n"); } if (defined $opt_c){ $configFile=$opt_c; } if (!(-e $configFile)){ ErrorExit("A configuration file was not found!\n"); } &Initialise($configFile); # Check the lock file $lockFile = TFMakeAbsoluteFilePath($Init{"receiver:lock file"},$home,$lockPath); if (!TFCreateProcessLock($lockFile)){ ErrorExit("Process is already running\n"); } &InitSerial(); # end of main #----------------------------------------------------------------------------- sub ShowHelp { print "Usage: $0 [OPTIONS] ..\n"; print " -c <file> set configuration file\n"; print " -d debug\n"; print " -h show this help\n"; print " -v show version\n"; print " The default configuration file is $configFile\n"; } #----------------------------------------------------------------------------- sub ErrorExit { my $message=shift; @_=gmtime(time()); printf "%02d/%02d/%02d %02d:%02d:%02d $message\n", $_[3],$_[4]+1,$_[5]%100,$_[2],$_[1],$_[0]; exit; } # ErrorExit #----------------------------------------------------------------------------- sub Debug { if ($opt_d){ print strftime("%H:%M:%S",gmtime)." $_[0]\n"; } } # Debug #---------------------------------------------------------------------------- sub Initialise { my $name=shift; # The name of the configuration file. # Define the parameters that MUST have values in the configuration file # note that all these values come in as lowercase, no matter how they are # written in the configuration file @required=( "paths:receiver data","receiver:file extension","receiver:port","receiver:status file", "receiver:pps offset","receiver:lock file"); %Init=&TFMakeHash2($name,(tolower=>1)); if (!%Init) { print "Couldn't open $name\n"; exit; } my $err; # Check that all required information is present $err=0; foreach (@required) { unless (defined $Init{$_}) { print STDERR "! No value for $_ given in $name\n"; $err=1; } } exit if $err; } # Initialise #---------------------------------------------------------------------------- sub InitSerial { # Open the serial port to the receiver $rxmask = ""; my($port) = $Init{"receiver:port"}; $port="/dev/$port" unless $port=~m#/#; $uucpLockPath="/var/lock"; if (defined $Init{"paths:uucp lock"}){ $uucpLockPath = $Init{"paths:uucp lock"}; } unless (`/usr/local/bin/lockport -d $uucpLockPath $port $0`==1) { printf "! Could not obtain lock on $port. Exiting.\n"; exit; } # Open port to NV08C UART B (COM2) at 115200 baud, 8 data bits, 1 stop bit, # odd parity, no flow control (see paragraph 2, page 8 of 91 in BINR # protocol specification). # To decipher the flags, look in the termios documentation $rx = &TFConnectSerial($port, (ispeed=>0010002,ospeed=>0010002,iflag=>IGNBRK, oflag=>0,lflag=>0,cflag=>CS8|CREAD|PARENB|PARODD|HUPCL|CLOCAL)); # Set up a mask which specifies this port for select polling later on vec($rxmask,fileno $rx,1)=1; print "> Port $port to NV08C (GPS) Rx is open\n"; # Wait a bit sleep(1); } #---------------------------------------------------------------------------- sub sendCmd { my($cmd) = shift; $cmd =~ s/\x10/\x10\x10/g; # 'stuff' (double) DLE in data print $rx "\x10".$cmd."\x10\x03"; # DLE at start, DLE/ETX at end # Wait 100 ms select (undef,undef,undef,0.1); } # SendCmd #---------------------------------------------------------------------------- sub stripDLEandETX { my($s) = @_; if(length($s) != 0){ my($len)=length($s); # strip off first character and last 2 characters $s = substr $s,1,$len-3; } # return the answer return $s; } # stripDLEandETX #----------------------------------------------------------------------------
openttp/openttp
software/gpscv/nvs/nv08info.pl
Perl
mit
6,112
#!/usr/bin/perl #use warnings; use Data::Dumper; use String::Util 'trim'; use File::DirWalk; use LWP::UserAgent; use URI::Escape; use JSON; my $ua = LWP::UserAgent->new; sub camel_to_underscore { $_ = shift; # Replace first capital by lowercase # if followed my lowercase. s/^([A-Z])([a-z])/lc($1).$2/e; # Substitute camelCase to camel_case s/([a-z])([A-Z])/$1.'_'.lc($2)/ge; return $_; } sub generate_test_parameters { my $base = shift @_; my $plugin_path = shift @_; my $path = $base . $plugin_path; my $plugin_name = $plugin_path; $plugin_name =~ s/.pm//g; $plugin_name =~ s/\//::/g; open my $PLUGINPM, "<", $path or die $!; my $plugin_info = {'name' => $plugin_name}; if ($plugin_name =~ /Spice/) { my @kickstart_arr = split('::',$plugin_name); my $kickstart = '/js/spice/'.$kickstart_arr[-1]; $kickstart = camel_to_underscore($kickstart); $kickstart = lc $kickstart; $plugin_info->{'kickstart'} = $kickstart; } my @examples = (); foreach $line (<$PLUGINPM>) { if ($line =~/(primary_example_queries|secondary_example_queries)/) { $line =~s/(primary_example_queries|secondary_example_queries)//g; $line =~ s/;//g; @eg = split(',', $line); foreach $e (@eg) { $e =~ s/(\"|\')//g; if (! ($e =~ '')) { push(@examples, trim($e)); } } } if ($line =~/zci/ && $line =~ /answer_type/) { $line =~ s/(zci|answer_type|=>)//g; $line =~s/(\"|\'|\;)//g; $plugin_info->{'answer_type'} = trim($line); } } $plugin_info->{'examples'} = \@examples; return $plugin_info; } sub walk_repo { my $path = shift @_; $path = $path . '/lib/'; my $dw = new File::DirWalk; @package_list = (); $dw->onDirEnter(sub { my ($dir) = @_; return File::DirWalk::SUCCESS; }); $dw->onFile(sub { my ($file) = @_; if ($file !~ /(Bundle|Role)/) { my @module = split($path, $file); push(@package_list,generate_test_parameters($path, $module[1])); } return File::DirWalk::SUCCESS; }); $dw->walk($path); return \@package_list; } sub test_query { my $test_subject = shift @_; my $verbose = shift @_; my $plugin_name = $test_subject->{'name'}; print "\n".$plugin_name."\n"; my $examples_ref = $test_subject->{'examples'}; my @examples = @{$examples_ref}; if ($examples =~ 0) { print "No Tests\n"; return; } if (exists $test_subject->{'answer_type'}) { my $answer_type = $test_subject->{'answer_type'}; #print @examples; foreach $ex (@examples) { my $cooked_ex = uri_escape($ex); my $url = 'https://api.duckduckgo.com?q='.$cooked_ex.'&o=json&no_html=1&d=0'; my $req = HTTP::Request->new(GET => $url); my $res = $ua->request($req); if ($res-> is_success){ my $test_res = from_json($res->content); if ($test_res->{"AnswerType"} =~ $answer_type) { print ' '. $ex . " Test OK\n"; } else { print ' '. $ex . " Test FAIL\n"; } } else { print " ". $ex . "Network Error\n"; } } } else { if ($plugin_name =~ /Goodie/) { return; } if (exists $test_subject->{'kickstart'}) { my $kickstart = $test_subject->{'kickstart'}; foreach $ex (@examples) { my $cooked_ex = uri_escape($ex); my $url = 'https://duckduckgo.com?q='.$cooked_ex; my $req = HTTP::Request->new(GET => $url); my $res = $ua->request($req); if ($res-> is_success){ if ($res->content =~ /\Q$kickstart\E/) { print ' '. $ex . " Test OK\n"; } else { print ' '. $ex . " Test FAIL\n"; } } else { print " ". $ex . "Network Error\n"; } } } } } my $repository = pop(@ARGV); if ($repository =~ /...\/$/) { my $last = chop($repository); } my $test1 = walk_repo($repository); foreach $test (@{$test1}) { #print Dumper($test); print test_query($test, 0); }
djinn/ddg-webtester
webtester.pl
Perl
mit
3,960
#!/opt/third-party/bin/perl use warnings; use strict; my $time1 = shift; my $time2 = shift; $time1 = convert_to_seconds($time1); $time2 = convert_to_seconds($time2); my $factor = $time1 / $time2; printf("Factor of %.2f\n", $factor); sub convert_to_seconds { my $time = shift; my $to_return; if ( $time =~ m/(\d*):(\d*)/ ) { $to_return = ($1 * 60) + $2; } elsif ( $time =~ m/\d+/ ) { $to_return = $time; } else { die "Could not parse time: $time\n"; } }
benbernard/HomeDir
bin/speedup.pl
Perl
mit
490
############################################################################## # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Library General Public License for more details. # # You should have received a copy of the GNU Library General Public # License along with this library; if not, write to the # Free Software Foundation, Inc., 59 Temple Place - Suite 330, # Boston, MA 02111-1307, USA. # # Copyright (C) 1998-2004 Jabber Software Foundation http://jabber.org/ # ############################################################################## package Net::Jabber::Debug; =head1 NAME Net::Jabber::Debug - Jabber Debug Library =head1 DESCRIPTION Net::Jabber::Debug inherits all of its methods from Net::XMPP::Debug. =head1 AUTHOR Ryan Eatmon =head1 COPYRIGHT This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut require 5.003; use strict; use FileHandle; use Carp; use Net::XMPP::Debug; use base qw( Net::XMPP::Debug ); use vars qw( $VERSION ); $VERSION = "2.0"; 1;
carlgao/lenga
images/lenny64-peon/usr/share/perl5/Net/Jabber/Debug.pm
Perl
mit
1,473
# Copyright 2008 Raphaël Hertzog <hertzog@debian.org> # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. package Dpkg::Source::CompressedFile; use strict; use warnings; use Dpkg::Compression; use Dpkg::Source::Compressor; use Dpkg::Gettext; use Dpkg::ErrorHandling qw(error syserr warning subprocerr); use POSIX; # Object methods sub new { my ($this, %args) = @_; my $class = ref($this) || $this; my $self = { "compression" => "auto" }; bless $self, $class; $self->{"compressor"} = Dpkg::Source::Compressor->new(); $self->{"add_comp_ext"} = $args{"add_compression_extension"} || $args{"add_comp_ext"} || 0; $self->{"allow_sigpipe"} = 0; if (exists $args{"filename"}) { $self->set_filename($args{"filename"}); } if (exists $args{"compression"}) { $self->set_compression($args{"compression"}); } if (exists $args{"compression_level"}) { $self->set_compression_level($args{"compression_level"}); } return $self; } sub reset { my ($self) = @_; %{$self} = (); } sub set_compression { my ($self, $method) = @_; if ($method ne "none" and $method ne "auto") { $self->{"compressor"}->set_compression($method); } $self->{"compression"} = $method; } sub set_compression_level { my ($self, $level) = @_; $self->{"compressor"}->set_compression_level($level); } sub set_filename { my ($self, $filename, $add_comp_ext) = @_; $self->{"filename"} = $filename; # Automatically add compression extension to filename if (defined($add_comp_ext)) { $self->{"add_comp_ext"} = $add_comp_ext; } if ($self->{"add_comp_ext"} and $filename =~ /\.$comp_regex$/) { warning("filename %s already has an extension of a compressed file " . "and add_comp_ext is active", $filename); } } sub get_filename { my $self = shift; my $comp = $self->{"compression"}; if ($self->{'add_comp_ext'}) { if ($comp eq "auto") { error("automatic detection of compression is " . "incompatible with add_comp_ext"); } elsif ($comp eq "none") { return $self->{"filename"}; } else { return $self->{"filename"} . "." . $comp_ext{$comp}; } } else { return $self->{"filename"}; } } sub use_compression { my ($self, $update) = @_; my $comp = $self->{"compression"}; if ($comp eq "none") { return 0; } elsif ($comp eq "auto") { $comp = get_compression_from_filename($self->get_filename()); $self->{"compressor"}->set_compression($comp) if $comp; } return $comp; } sub open_for_write { my ($self) = @_; my $handle; if ($self->use_compression()) { $self->{'compressor'}->compress(from_pipe => \$handle, to_file => $self->get_filename()); } else { open($handle, '>', $self->get_filename()) || syserr(_g("cannot write %s"), $self->get_filename()); } return $handle; } sub open_for_read { my ($self) = @_; my $handle; if ($self->use_compression()) { $self->{'compressor'}->uncompress(to_pipe => \$handle, from_file => $self->get_filename()); $self->{'allow_sigpipe'} = 1; } else { open($handle, '<', $self->get_filename()) || syserr(_g("cannot read %s"), $self->get_filename()); } return $handle; } sub cleanup_after_open { my ($self) = @_; $self->{"compressor"}->wait_end_process(nocheck => $self->{'allow_sigpipe'}); if ($self->{'allow_sigpipe'}) { unless (($? == 0) || (WIFSIGNALED($?) && (WTERMSIG($?) == SIGPIPE))) { subprocerr($self->{"compressor"}{"cmdline"}); } } } 1;
carlgao/lenga
images/lenny64-peon/usr/share/perl5/Dpkg/Source/CompressedFile.pm
Perl
mit
4,209
use strict; # files to be read my $org_file = "const_menu_org.c2"; my $menu_text_file = "const_menu_menu_text.c2"; my $menu_type_file = "const_menu_menu_type.c2"; my $menu_id_file = "const_menu_menu_id.c2"; my $menu_keypress_1_file = "const_menu_keypress_1.c2"; my $menu_keypress_2_file = "const_menu_keypress_2.c2"; my $menu_keypress_3_file = "const_menu_keypress_3.c2"; my $menu_keypress_NUM_file = "const_menu_keypress_NUM.c2"; my $menu_keypress_AST_file = "const_menu_keypress_ASTERIX.c2"; my $menu_variable1_1_file = "const_menu_variable1_1.c2"; my $menu_variable1_2_file = "const_menu_variable1_2.c2"; my $menu_variable1_3_file = "const_menu_variable1_3.c2"; my $menu_variable2_1_file = "const_menu_variable2_1.c2"; my $menu_variable2_2_file = "const_menu_variable2_2.c2"; my $menu_variable2_3_file = "const_menu_variable2_3.c2"; my $menu_screen_text_file = "const_menu_screen_text.c2"; my $menu_screen_id_file = "const_menu_screen_id.c2"; # translation files my $menu_text_translation_file = "const_menu_text.c2"; my $screen_text_translation_file = "const_screen_text.c2"; my $menu_id_translation_file = "const_menu_id.c2"; my $screen_id_translation_file = "const_screen_id.c2"; my %var_translation_file_hash; $var_translation_file_hash{"temp_ctrl"} = "..\\common_modules\\temp_ctrl.c2"; $var_translation_file_hash{"const_room_data"} = "const_room_data.c2"; $var_translation_file_hash{"const_output_blinds"} = "const_output_blinds.c2"; $var_translation_file_hash{"const_dimmer"} = "const_dimmer.c2"; $var_translation_file_hash{"const_house"} = "const_house.c2"; $var_translation_file_hash{"const_switches"} = "const_switches.c2"; # hashes to store info in my %MENU_hash; my %KEYPRESS_hash; my %MENU_TEXT_hash; my %MENU_ID_hash; my %SCREEN_ID_hash; my %VAR_ID_hash; ################################################################################# my @menu_text_file_content = (); my @menu_type_file_content = (); my @menu_id_file_content = (); my @menu_keypress_1_file_content = (); my @menu_keypress_2_file_content = (); my @menu_keypress_3_file_content = (); my @menu_keypress_NUM_file_content = (); my @menu_keypress_AST_file_content = (); my @menu_variable1_1_file_content = (); my @menu_variable1_2_file_content = (); my @menu_variable1_3_file_content = (); my @menu_variable2_1_file_content = (); my @menu_variable2_2_file_content = (); my @menu_variable2_3_file_content = (); my @menu_screen_text_file_content = (); my @menu_screen_id_file_content = (); my $item_count; my $hex_val; my $EOL_char; ################################################################################# # script start ################################################################################# # Extract name of script (without path) $0 =~ /([^\\]*)$/; my $script_name = $1; # read the input file; my @input_file_content = `type $org_file`;; my $value_keypress_num; my $value_keypress_ast; my $org_line; foreach $org_line(@input_file_content) { if(/^\s+\/\//) { # if this is a comment next; } $org_line =~ s/^\s*//g; # read defines if ($org_line =~ /const MENU/) { $org_line =~ /(\d);$/; $MENU_hash{MENU} = $1; # print "MENU = $MENU_hash{MENU}\n"; } elsif ($org_line =~ /const SCREEN/) { $org_line =~ /(\d);$/; $MENU_hash{SCREEN} = $1; # print "SCREEN = $MENU_hash{SCREEN}\n"; } if ($org_line =~ /const LEVEL_CHANGE_LEVEL_UP/) { $org_line =~ /(0x\d*);$/; $KEYPRESS_hash{LEVEL_CHANGE_LEVEL_UP} = $1; # print "LEVEL_CHANGE_LEVEL_UP = $KEYPRESS_hash{LEVEL_CHANGE_LEVEL_UP}\n"; } elsif ($org_line =~ /const LEVEL_CHANGE_NEXT_MENU/) { $org_line =~ /(0x\d*);$/; $KEYPRESS_hash{LEVEL_CHANGE_NEXT_MENU} = $1; # print "LEVEL_CHANGE_NEXT_MENU = $KEYPRESS_hash{LEVEL_CHANGE_NEXT_MENU}\n"; } elsif ($org_line =~ /const LEVEL_CHANGE_NO_CHANGE/) { $org_line =~ /(0x\d*);$/; $KEYPRESS_hash{LEVEL_CHANGE_NO_CHANGE} = $1; # print "LEVEL_CHANGE_NO_CHANGE = $KEYPRESS_hash{LEVEL_CHANGE_NO_CHANGE}\n"; } elsif ($org_line =~ /const LEVEL_CHANGE_REBUILD/) { $org_line =~ /(0x\d*);$/; $KEYPRESS_hash{LEVEL_CHANGE_REBUILD} = $1; # print "LEVEL_CHANGE_REBUILD = $KEYPRESS_hash{LEVEL_CHANGE_REBUILD}\n"; } # get the menu structure; if ($org_line =~ /MenuText\[i\]/) { push(@menu_text_file_content, $org_line); } elsif ($org_line =~ /Screen_Type/) { push(@menu_type_file_content, $org_line); } elsif ($org_line =~ /Menu_Id/) { push(@menu_id_file_content, $org_line); } elsif ($org_line =~ /KeyPress\[0\]/) { push(@menu_keypress_1_file_content, $org_line); } elsif ($org_line =~ /KeyPress\[1\]/) { push(@menu_keypress_2_file_content, $org_line); } elsif ($org_line =~ /KeyPress\[2\]/) { push(@menu_keypress_3_file_content, $org_line); } elsif ($org_line =~ /KeyPress\[3\]/) { push(@menu_keypress_NUM_file_content, $org_line); } elsif ($org_line =~ /KeyPress\[4\]/) { push(@menu_keypress_AST_file_content, $org_line); } elsif ($org_line =~ /Variable1\[0\]/) { push(@menu_variable1_1_file_content, $org_line); } elsif ($org_line =~ /Variable1\[1\]/) { push(@menu_variable1_2_file_content, $org_line); } elsif ($org_line =~ /Variable1\[2\]/) { push(@menu_variable1_3_file_content, $org_line); } elsif ($org_line =~ /Variable2\[0\]/) { push(@menu_variable2_1_file_content, $org_line); } elsif ($org_line =~ /Variable2\[1\]/) { push(@menu_variable2_2_file_content, $org_line); } elsif ($org_line =~ /Variable2\[2\]/) { push(@menu_variable2_3_file_content, $org_line); } elsif ($org_line =~ /ScreenText\[i\]/) { push(@menu_screen_text_file_content, $org_line); } elsif ($org_line =~ /ScreenId\[i\]/) { push(@menu_screen_id_file_content, $org_line); } } ################################################################################# # read translation files ################################################################################# my $entry; my $key; my $value; open(IN, "<$menu_text_translation_file") or die "Can not open $menu_text_translation_file\n"; while (<IN>) { if(/^\s+\/\//) { # if this is a comment next; } if(/const.*?=.*?\".*?\"/) { $entry = $_; $entry =~ /const\s([\w]*)\s*=\s*\"([0-9äöüÄÖÜ\(\)\/\.\ß\&\w\s\:]*)\"/; $key = $1; $value = "\"".$2."\""; $MENU_TEXT_hash{$key} = $value; # print "key = $key\tvalue = $MENU_TEXT_hash{$key}\n"; } } close(IN); open(IN, "<$screen_text_translation_file") or die "Can not open $screen_text_translation_file\n"; while (<IN>) { if(/^\s+\/\//) { # if this is a comment next; } if(/const.*?=.*?\".*?\"/) { $entry = $_; $entry =~ /const\s([\w]*)\s*=\s*\"([0-9äöüÄÖÜ\(\)\/\.\ß\&\w\s:]*)\"/; $key = $1; $value = "\"".$2."\""; $MENU_TEXT_hash{$key} = $value; # print "key = $key\tvalue = $MENU_TEXT_hash{$key}\n"; } } close(IN); #################################################################### open(IN, "<$menu_id_translation_file") or die "Can not open $menu_id_translation_file\n"; while (<IN>) { if(/^\s+\/\//) { # if this is a comment next; } if(/const.*?=/) { $entry = $_; $entry =~ /const\s([\w]*)\s*=\s*?([0-9A-Fa-fx]*);/; $key = $1; $value = $2; $MENU_ID_hash{$key} = $value; # print "key = $key\tvalue = $MENU_ID_hash{$key}\n"; } } close(IN); #################################################################### my $increase_val; open(IN, "<$screen_id_translation_file") or die "Can not open $screen_id_translation_file\n"; while (<IN>) { if(/^\s+\/\//) { # if this is a comment next; } if(/const.*?=/) { $entry = $_; # print $entry; $entry =~ /const\s*([\w]*)\s*=\s*([\w]*)\s*\+\s*(\d);/; if($1 eq '') { # first value; $entry =~ /const\s([\w]*)\s*=\s*([x\d]*)/; $key = $1; $value = hex($2); $increase_val = $0; $hex_val = sprintf("0x%02X",$value); $SCREEN_ID_hash{$key} = $hex_val; } else { $key = $1; $value = $2; $increase_val = $3; $hex_val = sprintf("0x%02X",hex($SCREEN_ID_hash{$value}) + $increase_val); $SCREEN_ID_hash{$key} = $hex_val; } # print "key = $key\tvalue = $SCREEN_ID_hash{$key}\tincrease_val = $increase_val\n"; } } close(IN); #################################################################### my $file_key; foreach $file_key (keys %var_translation_file_hash) { # print "checking file $var_translation_file_hash{$file_key}\n"; open(IN, "<$var_translation_file_hash{$file_key}") or die "Can not open $var_translation_file_hash{$file_key}\n"; while (<IN>) { if(/^\s+\/\//) { # if this is a comment next; } if(/const.*?=/) { $entry = $_; # print $entry; if($file_key eq "const_house") { # read simple defines $entry =~ /const\s([\w]*)\s*=\s*([x\da-fA-F]*)/; # print "simple entry = $entry"; $key = $1; $value = $2; # print "\tkey = $key - value = $value\n\n"; if($1 eq '') { # read array entries # print "array entry = $entry"; $entry =~ /const\s([\w]*)\[\]\s*=\s*(\w*),/; $key = $1; if(!exists($VAR_ID_hash{$2})) { die "key $2 does not exist for $VAR_ID_hash{$2}\n"; } $value = $VAR_ID_hash{$2}; # print "\tkey1 = $key - \tkey2 = $2 - value = $value\n\n"; # sleep(1); } } else { $entry =~ /const\s([\w]*)\s*=\s*([x\da-fA-F]*)/; $key = $1; $value = $2; } $VAR_ID_hash{$key} = $value; # print "file = $var_translation_file_hash{$file_key}\tkey = $key\tvalue = $VAR_ID_hash{$key}\n"; } } close(IN); } ######################################################## # print file ------------- const_menu_menu_text.c2 ######################################################## $item_count = 0; open (OUT, ">$menu_text_file"); print OUT "/* generated file from $script_name*/ const MENU_TEXT[] ="; foreach $entry(@menu_text_file_content) { if($item_count == $#menu_text_file_content) { $EOL_char = ";"; } else { $EOL_char = ","; } $item_count++; $hex_val = sprintf("%X",$item_count); # extract the key value $entry =~ /const_menu_text\.(\w*);/; # print $entry; $key = $1; print OUT "/*,$item_count,-,$hex_val,const_menu_text\.$key,/* generated Element*/$MENU_TEXT_hash{$key}$EOL_char\n" } close(OUT); ######################################################## # print file ------------- const_menu_menu_type.c2 ######################################################## $item_count = 0; open (OUT, ">$menu_type_file"); print OUT "/* generated file from $script_name*/ const MENU = 1; const SCREEN = 2; const MENU_TYPE[] ="; foreach $entry(@menu_type_file_content) { if($item_count == $#menu_type_file_content) { $EOL_char = ";"; } else { $EOL_char = ","; } $item_count++; $hex_val = sprintf("%X",$item_count); if($entry =~ /MENU/) { print OUT "/*,$item_count,-,$hex_val,MENU,- generated Element*/$MENU_hash{MENU}$EOL_char\n"; } elsif($entry =~ /SCREEN/) { print OUT "/*,$item_count,-,$hex_val,SCREEN,- generated Element*/$MENU_hash{SCREEN}$EOL_char\n"; } else { close(OUT); die "unknown element: $entry\n"; } } close(OUT); ######################################################## # print file ------------- const_menu_menu_id.c2 ######################################################## $item_count = 0; open (OUT, ">$menu_id_file"); print OUT "/* generated file from $script_name*/ const MENU_ID[] ="; foreach $entry(@menu_id_file_content) { # print $entry; if($item_count == $#menu_id_file_content) { $EOL_char = ";"; } else { $EOL_char = ","; } $item_count++; $hex_val = sprintf("%X",$item_count); # extract the key value $entry =~ /const_menu_id\.(\w*);/; # print $entry; $key = $1; print OUT "/*,$item_count,-,$hex_val,const_menu_id\.$key,- generated Element*/$MENU_ID_hash{$key}$EOL_char\n" } print OUT "\nconst NUM_OF_MENUS = $item_count;\n"; close(OUT); ######################################################## # print file ------------- const_menu_keypress_1.c2 ######################################################## my $line = "/* generated file from $script_name*/ const MENU_KEYPRESS_1[] ="; write_keyPress_files("const_menu_keypress_1.c2", $line, $#menu_keypress_1_file_content, \@menu_keypress_1_file_content); ######################################################## # print file ------------- const_menu_keypress_2.c2 ######################################################## $line = "/* generated file from $script_name*/ const MENU_KEYPRESS_2[] ="; write_keyPress_files("const_menu_keypress_2.c2", $line, $#menu_keypress_2_file_content, \@menu_keypress_2_file_content); ######################################################## # print file ------------- const_menu_keypress_3.c2 ######################################################## $line = "/* generated file from $script_name*/ const MENU_KEYPRESS_3[] ="; write_keyPress_files("const_menu_keypress_3.c2", $line, $#menu_keypress_3_file_content, \@menu_keypress_3_file_content); ######################################################## # print file ------------- const_menu_keypress_Asterix.c2 ######################################################## $line = "/* generated file from $script_name*/ const MENU_KEYPRESS_ASTERIX[] ="; write_keyPress_files("const_menu_keypress_AST.c2", $line, $#menu_keypress_NUM_file_content, \@menu_keypress_NUM_file_content); ######################################################## # print file ------------- const_menu_keypress_NUM.c2 ######################################################## $line = "/* generated file from $script_name*/ const MENU_KEYPRESS_NUM[] ="; write_keyPress_files("const_menu_keypress_NUM.c2", $line, $#menu_keypress_AST_file_content, \@menu_keypress_AST_file_content); ######################################################## # print file ------------- const_menu_keypress_NUM.c2 ######################################################## $line = "/* generated file from $script_name*/ const MENU_VARIABLE1_1[] ="; write_keyPress_files("const_menu_variable1_1.c2", $line, $#menu_variable1_1_file_content, \@menu_variable1_1_file_content); ######################################################## # print file ------------- const_menu_keypress_NUM.c2 ######################################################## $line = "/* generated file from $script_name*/ const MENU_VARIABLE1_2[] ="; write_keyPress_files("const_menu_variable1_2.c2", $line, $#menu_variable1_2_file_content, \@menu_variable1_2_file_content); ######################################################## # print file ------------- const_menu_keypress_NUM.c2 ######################################################## $line = "/* generated file from $script_name*/ const MENU_VARIABLE1_3[] ="; write_keyPress_files("const_menu_variable1_3.c2", $line, $#menu_variable1_3_file_content, \@menu_variable1_3_file_content); ######################################################## # print file ------------- const_menu_keypress_NUM.c2 ######################################################## $line = "/* generated file from $script_name*/ const MENU_VARIABLE2_1[] ="; write_keyPress_files("const_menu_variable2_1.c2", $line, $#menu_variable2_1_file_content, \@menu_variable2_1_file_content); ######################################################## # print file ------------- const_menu_keypress_NUM.c2 ######################################################## $line = "/* generated file from $script_name*/ const MENU_VARIABLE2_2[] ="; write_keyPress_files("const_menu_variable2_2.c2", $line, $#menu_variable2_2_file_content, \@menu_variable2_2_file_content); ######################################################## # print file ------------- const_menu_keypress_NUM.c2 ######################################################## $line = "/* generated file from $script_name*/ const MENU_VARIABLE2_3[] ="; write_keyPress_files("const_menu_variable2_3.c2", $line, $#menu_variable2_3_file_content, \@menu_variable2_3_file_content); ######################################################## # print file ------------- const_menu_screen_id.c2 ######################################################## $item_count = 0; open (OUT, ">$menu_screen_id_file"); print OUT "/* generated file from const_menu.xls*/ const SCREEN_ID[] ="; foreach $entry(@menu_screen_id_file_content) { # print $entry; if($item_count == $#menu_screen_id_file_content) { $EOL_char = ";"; } else { $EOL_char = ","; } $item_count++; $hex_val = sprintf("%X",$item_count); # extract the key value $entry =~ /const_screen_id\.(\w*);/; # print $entry; $key = $1; print OUT "/*,$item_count,-,$hex_val,const_screen_id\.$key,- generated Element*/$SCREEN_ID_hash{$key}$EOL_char\n" } print OUT "\nconst NUM_OF_SCREENS = $item_count;\n"; close(OUT); ######################################################## # print file ------------- const_menu_screen_text.c2 ######################################################## $item_count = 0; open (OUT, ">$menu_screen_text_file"); print OUT "/* generated file from const_menu.xls*/ const SCREEN_TEXT[] ="; foreach $entry(@menu_screen_text_file_content) { # print $entry; if($item_count == $#menu_screen_text_file_content) { $EOL_char = ";"; } else { $EOL_char = ","; } $item_count++; $hex_val = sprintf("%X",$item_count); # extract the key value $entry =~ /const_(menu|screen)_text\.(\w*);/; # print $entry; my $kind = $1; $key = $2; print OUT "/*,$item_count,-,$hex_val,const_${kind}_text\.$key,- generated Element*/$MENU_TEXT_hash{$key}$EOL_char\n" } print OUT "\nconst NUM_OF_MENUS = $item_count;\n"; close(OUT); ############################################################################### # sub progs ############################################################################### sub write_keyPress_files { my $file = @_[0]; my $first_line = @_[1]; my $num_of_entries = @_[2]; my $content = @_[3]; $item_count = 0; open (OUT, ">$file") or die "Can not open $file\n"; print OUT $first_line; foreach $entry(@$content) { # print $entry; if($item_count == $num_of_entries) { $EOL_char = ";"; } else { $EOL_char = ","; } $item_count++; $hex_val = sprintf("%X",$item_count); if($entry =~ /const_menu_id/) { # extract the key value $entry =~ /const_menu_id\.(\w*);/; # print "$1\n"; $key = $1; if(!exists($MENU_ID_hash{$key})) { die "key $key does not exist for entry $entry\n"; } print OUT "/*,$item_count,-,$hex_val,const_menu_id\.$key,- generated Element*/$MENU_ID_hash{$key}$EOL_char\n" } elsif($entry =~ /const_screen_id/) { # extract the key value $entry =~ /const_screen_id\.(\w*);/; # print "$1\n"; $key = $1; if(!exists($SCREEN_ID_hash{$key})) { die "key $key does not exist for entry $entry\n"; } print OUT "/*,$item_count,-,$hex_val,const_screen_id\.$key,- generated Element*/$SCREEN_ID_hash{$key}$EOL_char\n" } else { my $found = 0; foreach $file_key (keys %var_translation_file_hash) { if($entry =~ /$file_key/) { # extract the key value # print $entry; $entry =~ /$file_key\.(\w*)[;\[]/; # print "$file_key - $1\n"; $key = $1; $found = 1; if(!exists($VAR_ID_hash{$key})) { die "key $key does not exist for entry $entry\n"; } print OUT "/*,$item_count,-,$hex_val,$file_key\.$key,- generated Element*/$VAR_ID_hash{$key}$EOL_char\n" } } if($found == 0) { close(OUT); print "$entry\n"; die "unknown id type in $file\n"; } } } close(OUT); }
Rosi2143/HSHSB3_CC2
CC2_Projects/Haus_CC2/consts/__const_menu_process.pl
Perl
mit
21,187
#!/usr/bin/perl use Getopt::Long; # Slave machines array. We don't need the master as this script will be executed on master. my @machines = ( 'titanium.dnsdynamic.net', 'tungsten.dnsdynamic.net', 'silicon.dnsdynamic.net' ); my $defaultUser = 'hduser'; my $jdkSymlink = '/opt/jdk'; my $targetJDK = undef; my $clusterwide = undef; my $auto = undef; my $failFlag = undef; GetOptions ( "jdk=s" => \$targetJDK, "all" => \$clusterwide, "auto" => \$auto ); if($targetJDK){ if(!-d $targetJDK){ die("$targetJDK not found. Cannot continue."); } if( -l $jdkSymlink ){ if(!$auto){display("Removing old symlik...");} my $command = "sudo rm $jdkSymlink"; my $rc = system($command); if($rc == 0){ if(!$auto){display("Symlink removed.");} } else { die("Failed to remove symlink."); } } if(!$auto){display("Creating new symlink...");} my $command = "sudo ln -s $targetJDK $jdkSymlink"; my $rc = system($command); if($rc == 0){ if(!$auto){display("Symlink created.");} else {display("success");} } else { die("fail"); } } if($clusterwide){ foreach my $machine (@machines){ my $rcommand = '/home/hduser/changejdks.pl -auto -jdk ' . $targetJDK; my $command = 'ssh ' . $defaultUser . '@' . $machine . ' "' . $rcommand . '";'; my $output = `$command`; chomp($output); if($output ne "success"){ if(!$auto){display("Failed to change jdk on machine $machine. Output was:\n\t$output");} if($auto){print "fail"; $failFlag = 1;} } else { if(!$auto){display("$machine changed it's JDK successfully.");} print "success"; } } } if(defined($failFlag)){ exit 1; } else { exit 0; } sub display { my $str = shift; print $str . "\n"; }
manthanhd/gravity
scripts/master/changejdks.pl
Perl
mit
1,746
package MarpaX::Languages::PowerBuilder::SRJ; use base qw(MarpaX::Languages::PowerBuilder::base); #a SRJ parser by Nicolas Georges #helper methods #retrieve pbd entries sub pbd { @{$_[0]->value->{pbd}} } #retrieve object entries sub obj { @{$_[0]->value->{obj}} } #build and executable options sub executable_name { $_[0]->value->{exe}[0] } sub application_pbr { $_[0]->value->{exe}[1] } sub prompt_for_overwrite { $_[0]->value->{exe}[2] } sub rebuild_type { $_[0]->value->{exe}[3] ? 'full' : 'incremental' } sub rebuild_type_int { $_[0]->value->{exe}[3] } sub windows_classic_style { $_[0]->value->{exe}[4] ? 0 : 1 } sub new_visual_style_controls { $_[0]->value->{exe}[4] } #code generation options #TODO: find meaning of {cmp}[3, 5 and 7] sub build_type { $_[0]->value->{cmp}[0] ? 'machinecode' : '' } #empty is for pcode sub build_type_int { $_[0]->value->{cmp}[0] } sub with_error_context { $_[0]->value->{cmp}[1] } sub with_trace_information { $_[0]->value->{cmp}[2] } sub optimisation { qw(speed space none)[ $_[0]->value->{cmp}[4] ] // '?' } sub optimisation_int { $_[0]->value->{cmp}[4] } sub enable_debug_symbol { $_[0]->value->{cmp}[6] } #manifest information sub manifest_type { qw(none embedded external)[$_[0]->value->{man}[0]] // '?' } sub manifest_type_int { $_[0]->value->{man}[0] } sub execution_level { $_[0]->value->{man}[1] } sub access_protected_sys_ui { $_[0]->value->{man}[2] ? 'true' : 'false' } sub access_protected_sys_ui_int { $_[0]->value->{man}[2] } sub manifestinfo_string { #this string is usable in orcascript for the manifestinfo argument of the 'set exeinfo property' command my $self = shift; my $manifest = join ';', @{ $self->value->{man} }; $manifest =~ s/1$/true/ or $manifest =~ s/0$/false/; return $manifest; } #others sub product_name { $_[0]->value->{prd}[0] } sub company_name { $_[0]->value->{com}[0] } sub description { $_[0]->value->{des}[0] } sub copyright { $_[0]->value->{cpy}[0] } sub product_version_string { $_[0]->value->{pvs}[0] } sub product_version_number { join('.', @{ $_[0]->value->{pvn} }) } sub product_version_raw { join(',', @{ $_[0]->value->{pvn} }) } sub product_version_numbers { @{ $_[0]->value->{pvn} } } sub file_version_string { $_[0]->value->{fvs}[0] } sub file_version_number { join('.', @{ $_[0]->value->{fvn} }) } sub file_version_raw { join(',', @{ $_[0]->value->{fvn} }) } sub file_version_numbers { @{ $_[0]->value->{fvn} } } #Grammar action methods sub project { my ($ppa, $items) = @_; my %attrs; ITEM: for(@$items){ my $item = $_->[0]; my ($name, @children) = @$item; if($name =~ /^(PBD|OBJ)$/i){ push @{$attrs{$name}}, \@children; } else{ $attrs{$name} = \@children; } } return \%attrs; } sub compiler{ my ($ppa, $ary) = @_; return [ cmp => @$ary ]; } sub string { my ($ppa, $str) = @_; return $str; } sub integer { my ($ppa, @digits) = @_; return join '', @digits; } 1;
sebkirche/MarpaX-Languages-PowerBuilder
lib/MarpaX/Languages/PowerBuilder/SRJ.pm
Perl
mit
3,253
name('transpiler'). title('A universal translator for programming languages'). version('0.1'). download('https://github.com/jarble/transpiler/archive/v0.1.zip'). author('Anderson Green','jarble@gmail.com'). packager('Anderson Green','jarble@gmail.com'). maintainer('Anderson Green','jarble@gmail.com'). home('https://github.com/jarble/transpiler/').
jarble/transpiler
pack.pl
Perl
mit
354
use warnings; use strict; package Mail::IMAPClient::MessageSet; =head1 NAME Mail::IMAPClient::MessageSet - ranges of message sequence nummers =cut use overload '""' => "str" , '.=' => sub {$_[0]->cat($_[1])} , '+=' => sub {$_[0]->cat($_[1])} , '-=' => sub {$_[0]->rem($_[1])} , '@{}' => "unfold" , fallback => 1; sub new { my $class = shift; my $range = $class->range(@_); bless \$range, $class; } sub str { overload::StrVal( ${$_[0]} ) } sub _unfold_range($) # { my $x = shift; return if $x =~ m/[^0-9,:]$/; $x =~ s/\:/../g; eval $x; } { map { /(\d+)\s*\:\s*(\d+)/ ? ($1..$2) : $_ } split /\,/, shift; } sub rem { my $self = shift; my %delete = map { ($_ => 1) } map { _unfold_range $_ } @_; $$self = $self->range(grep {not $delete{$_}} $self->unfold); $self; } sub cat { my $self = shift; $$self = $self->range($$self, @_); $self; } sub range { my $self = shift; my @msgs; foreach my $m (@_) { defined $m && length $m or next; foreach my $mm (ref $m eq 'ARRAY' ? @$m : $m) { push @msgs, _unfold_range $mm; } } @msgs or return undef; @msgs = sort {$a <=> $b} @msgs; my $low = my $high = shift @msgs; my @ranges; foreach my $m (@msgs) { next if $m == $high; # double if($m == $high + 1) { $high = $m } else { push @ranges, $low == $high ? $low : "$low:$high"; $low = $high = $m; } } push @ranges, $low == $high ? $low : "$low:$high" ; join ",", @ranges; } sub unfold { my $self = shift; wantarray ? ( _unfold_range $$self ) : [ _unfold_range $$self ]; } =head1 SYNOPSIS my @msgs = $imap->search("SUBJECT","Virus"); # returns 1,3,4,5,6,9,10 my $msgset = Mail::IMAPClient::MessageSet->new(@msgs); print $msgset; # prints "1,3:6,9:10" # add message 14 to the set: $msgset += 14; print $msgset; # prints "1,3:6,9:10,14" # add messages 16,17,18,19, and 20 to the set: $msgset .= "16,17,18:20"; print $msgset; # prints "1,3:6,9:10,14,16:20" # Hey, I didn't really want message 17 in there; let's take it out: $msgset -= 17; print $msgset; # prints "1,3:6,9:10,14,16,18:20" # Now let's iterate over each message: for my $msg (@$msgset) { print "$msg\n"; # Prints: "1\n3\n4\n5\n6..16\n18\n19\n20\n" } print join("\n", @$msgset)."\n"; # same simpler local $" = "\n"; print "@$msgset\n"; # even more simple =head1 DESCRIPTION The B<Mail::IMAPClient::MessageSet> module is designed to make life easier for programmers who need to manipulate potentially large sets of IMAP message UID's or sequence numbers. This module presents an object-oriented interface into handling your message sets. The object reference returned by the L<new> method is an overloaded reference to a scalar variable that contains the message set's compact RFC2060 representation. The object is overloaded so that using it like a string returns this compact message set representation. You can also add messages to the set (using either a '.=' operator or a '+=' operator) or remove messages (with the '-=' operator). And if you use it as an array reference, it will humor you and act like one by calling L<unfold> for you. RFC2060 specifies that multiple messages can be provided to certain IMAP commands by separating them with commas. For example, "1,2,3,4,5" would specify messages 1, 2, 3, 4, and (you guessed it!) 5. However, if you are performing an operation on lots of messages, this string can get quite long. So long that it may slow down your transaction, and perhaps even cause the server to reject it. So RFC2060 also permits you to specifiy a range of messages, so that messages 1, 2, 3, 4 and 5 can also be specified as "1:5". This is where B<Mail::IMAPClient::MessageSet> comes in. It will convert your message set into the shortest correct syntax. This could potentially save you tons of network I/O, as in the case where you want to fetch the flags for all messages in a 10000 message folder, where the messages are all numbered sequentially. Delimited as commas, and making the best-case assumption that the first message is message "1", it would take 48893 bytes to specify the whole message set using the comma-delimited method. To specify it as a range, it takes just seven bytes (1:10000). Note that the L<Mail::IMAPClient> B<Range> method can be used as a short-cut to specifying C<Mail::IMAPClient::MessageSet-E<gt>new(@etc)>.) =head1 CLASS METHODS The only class method you need to worry about is B<new>. And if you create your B<Mail::IMAPClient::MessageSet> objects via L<Mail::IMAPClient>'s B<Range> method then you don't even need to worry about B<new>. =head2 new Example: my $msgset = Mail::IMAPClient::MessageSet->new(@msgs); The B<new> method requires at least one argument. That argument can be either a message, a comma-separated list of messages, a colon-separated range of messages, or a combination of comma-separated messages and colon-separated ranges. It can also be a reference to an array of messages, comma-separated message lists, and colon separated ranges. If more then one argument is supplied to B<new>, then those arguments should be more message numbers, lists, and ranges (or references to arrays of them) just as in the first argument. The message numbers passed to B<new> can really be any kind of number at all but to be useful in a L<Mail::IMAPClient> session they should be either message UID's (if your I<Uid> parameter is true) or message sequence numbers. The B<new> method will return a reference to a B<Mail::IMAPClient::MessageSet> object. That object, when double quoted, will act just like a string whose value is the message set expressed in the shortest possible way, with the message numbers sorted in ascending order and with duplicates removed. =head1 OBJECT METHODS The only object method currently available to a B<Mail::IMAPClient::MessageSet> object is the L<unfold> method. =head2 unfold Example: my $msgset = $imap->Range( $imap->messages ) ; my @all_messages = $msgset->unfold; The B<unfold> method returns an array of messages that belong to the message set. If called in a scalar context it returns a reference to the array instead. =head1 OVERRIDDEN OPERATIONS B<Mail::IMAPClient::MessageSet> overrides a number of operators in order to make manipulating your message sets easier. The overridden operations are: =head2 stringify Attempts to stringify a B<Mail::IMAPClient::MessageSet> object will result in the compact message specification being returned, which is almost certainly what you will want. =head2 Auto-increment Attempts to autoincrement a B<Mail::IMAPClient::MessageSet> object will result in a message (or messages) being added to the object's message set. Example: $msgset += 34; # Message #34 is now in the message set =head2 Concatenate Attempts to concatenate to a B<Mail::IMAPClient::MessageSet> object will result in a message (or messages) being added to the object's message set. Example: $msgset .= "34,35,36,40:45"; # Messages 34,35,36,40,41,42,43,44,and 45 are now in the message set The C<.=> operator and the C<+=> operator can be used interchangeably, but as you can see by looking at the examples there are times when use of one has an aesthetic advantage over use of the other. =head2 Autodecrement Attempts to autodecrement a B<Mail::IMAPClient::MessageSet> object will result in a message being removed from the object's message set. Examples: $msgset -= 34; # Message #34 is no longer in the message set $msgset -= "1:10"; # Messages 1 through 10 are no longer in the message set If you attempt to remove a message that was not in the original message set then your resulting message set will be the same as the original, only more expensive. However, if you attempt to remove several messages from the message set and some of those messages were in the message set and some were not, the additional overhead of checking for the messages that were not there is negligable. In either case you get back the message set you want regardless of whether it was already like that or not. =head1 AUTHOR David J. Kernen The Kernen Consulting Group, Inc =head1 COPYRIGHT Copyright 1999, 2000, 2001, 2002 The Kernen Group, Inc. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of either: =over 4 =item a) the "Artistic License" which comes with this Kit, or =item b) the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version. =back This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See either the GNU General Public License or the Artistic License for more details. All your base are belong to us. =cut 1;
carlgao/lenga
images/lenny64-peon/usr/share/perl5/Mail/IMAPClient/MessageSet.pm
Perl
mit
9,027
package Alatar::PostgreSQL::Extractors::PgFunctionExtractor; use Data::Dumper; use strict; use String::Util qw(trim); use Regexp::Common; use Alatar::Configuration; use Alatar::PostgreSQL::Extractors::PgExtractor; use Alatar::PostgreSQL::Extractors::PgTableExtractor; use Alatar::PostgreSQL::PgKeywords; use Alatar::Model::SqlFunction; use Alatar::Model::SqlArgument; use Alatar::Model::SqlCursor; use Alatar::Model::SqlRequest; use Alatar::Model::Refs::SqlFunctionReference; use Alatar::Model::Refs::SqlDataTypeReference; our @ISA = qw(Alatar::PostgreSQL::Extractors::PgExtractor); sub new { my ($class,$owner,$code) = @_; my $this = $class->SUPER::new($owner,$code); bless($this,$class); return $this; } # actions # -------------------------------------------------- # Return the number of function's arguments sub _extractArgumentsNumber { my ($this,$arguments) = @_; my @args = $arguments =~ /^\((.*?)\)$/g; if($args[0] eq '') { return 0; } else { my @commas = $args[0] =~ /(\,)/g; my $numberOfCommas = scalar(@commas); if($numberOfCommas >= 1) { return $numberOfCommas + 1; } else { return 1; } } } # Create cursor definitions contained in a function sub _extractCursorDefinitions { my ($this) = @_; my @cursors = $this->{entity}->getDeclareSection() =~ /(\w*)\s+CURSOR\s+(.*)FOR\s+(.*\;)/gi; for(my $i = 0;$i <= ($#cursors - 1);$i+=2) { $this->{entity}->addRequest(Alatar::Model::SqlCursor->new($this->{entity},$cursors[$i],$cursors[$i + 1],$cursors[$i + 2])); push(@{$this->{entity}->{cursors}},$cursors[$i]); } } # Return a formated name for cursors and request sub _buildName { my ($this,$type,$id) = @_; return ($this->{entity}->getName() . '_' . $this->{entity}->getArgumentsNumber() . '_' . $type . '_' . $id); } sub _extractRequests { my ($this) = @_; my $reqNumber; my @requests = $this->{entity}->getBodySection() =~ /(SELECT|UPDATE|INSERT|DELETE)\s(.*?)(;)/gi; $reqNumber = 0; for(my $i = 0;$i <= ($#requests - 2);$i+=3) { my $request = "$requests[$i] $requests[$i + 1];"; # If the exclude option is true, the SQL request is deleted to avoid the referencement of the invoked functions if(Alatar::Configuration->getOption('exclude')) { my $reqPattern = quotemeta($request); my $body = $this->{entity}->getBodySection(); $this->{entity}->setBodySection($body =~ s/$reqPattern//gi); } $reqNumber = $reqNumber + 1; $this->{entity}->addRequest(Alatar::Model::SqlRequest->new($this->{entity},$this->_buildName('R',$reqNumber),$request)); } } # validate that the function name is not a cursor name sub _isNotCursorName { my ($this,$cursorName) = @_; return !(grep {$_ eq $cursorName} @{$this->{entity}->{cursors}}) } sub _extractInvokedFunctions { my ($this,$code) = @_; my @funcs = $code =~ /(\w+)$RE{balanced}{-parens=>'( )'}/g; for(my $i = 0;$i <= ($#funcs - 1);$i+=2) { # Before to add it at the invoked functions list, we must validate that it's not a cursor and it's not a PostgreSQL keyword if($this->_isNotCursorName($funcs[$i]) && Alatar::PostgreSQL::PgKeywords->isNotKeyword($funcs[$i])) { $this->{entity}->addInvokedFunction(Alatar::Model::Refs::SqlFunctionReference->new($this->{entity},$funcs[$i],$this->_extractArgumentsNumber($funcs[$i+1]))); $this->_extractInvokedFunctions($funcs[$i+1]); } } } sub _extractNewOldColumns { my ($this,$code) = @_; my @news = $code =~ /NEW.([\w\_\$\d]+)/gi; my @olds = $code =~ /OLD.([\w\_\$\d]+)/gi; foreach my $new (@news) { $this->{entity}->addNewColumn($new); } foreach my $old (@olds) { $this->{entity}->addOldColumn($old); } } sub _extractObject { my ($this,$code) = @_; my @items = $code =~ /(\"?(\w+)\"?\(((\w*\s\w*),?)*\))/i; $this->{entity} = Alatar::Model::SqlFunction->new($this->{owner},$items[1]); $this->{entity}->setSignature($items[0]); @items = $code =~ /RETURNS\s(\w+\s?\w*)/i; if(@items) { $this->{entity}->setReturnType(Alatar::Model::Refs::SqlDataTypeReference->new($this->{entity},$items[0])); } @items = $code =~ /LANGUAGE\s*(\w*)/i; if(@items) { $this->{entity}->setLanguage($items[0]); } # Extract the declare and the body sections # only for pg/plsql functions my ($declare) = $code =~ /DECLARE(.*)BEGIN/i; if($declare) { $this->{entity}->setDeclareSection($declare); } my ($body) = $code =~ /BEGIN\s(.*)/i; if($body) { $this->{entity}->setBodySection($body); } # Extract the function arguments my @params = $this->{entity}->getSignature() =~ /(\w+\s\w+\s?\w*)/g; foreach my $param (@params) { my @p = $param =~ /(\w+)\s(\w+\s?\w*)/g; $this->{entity}->addArg(Alatar::Model::SqlArgument->new($this->{entity},$p[0],Alatar::Model::Refs::SqlDataTypeReference->new($this->{entity},$p[1]))); } if(@params) { $this->{entity}->setArgumentsNumber(scalar(@params)); } else { $this->{entity}->setArgumentsNumber(0); } $this->_extractCursorDefinitions(); $this->_extractRequests(); $this->_extractInvokedFunctions($this->{entity}->getBodySection()); if($this->{entity}->getReturnType()->getName() eq 'trigger') { $this->_extractNewOldColumns($this->{entity}->getBodySection()); } } 1;
olivierauverlot/alatar
Alatar/PostgreSQL/Extractors/PgFunctionExtractor.pm
Perl
mit
5,134
:- module(tuples,[tuples/2,write_tuples/2]). :- use_module(library(lists),[member/2,append/3]). tuples(XDRS,Tuples):- XDRS=xdrs(_Words,_POS,_NEtags,DRS), numbervars(DRS,0,_), conditions(DRS,[],C), setof(Tuple,tuple(C,Tuple),Tuples), !. tuples(_,[]). /* ======================================================================= Get all conditions from a DRS ======================================================================= */ conditions(drs(_,[]),C,C). conditions(drs(D,[X|L]),C1,[X|C2]):- conditions(drs(D,L),C1,C2). conditions(smerge(B1,B2),C1,C3):- conditions(B1,C1,C2), conditions(B2,C2,C3). conditions(merge(B1,B2),C1,C3):- conditions(B1,C1,C2), conditions(B2,C2,C3). conditions(alfa(_,B1,B2),C1,C3):- conditions(B1,C1,C2), conditions(B2,C2,C3). /* ======================================================================= Output tuples to stream ======================================================================= */ write_tuples([],_). write_tuples([tuple(A,B,C)|L],Stream):- format(Stream,'~w ~w ~w~n',[A,B,C]), write_tuples(L,Stream). /* ======================================================================= Find tuple in DRS-conditions ======================================================================= */ tuple(C,tuple([XX:1|XM],[YY:2|YM],[EE,0:ArgX:1,0:ArgY:2|Mod])):- event(C,E,EE), member(ArgX:ArgY,[agent:theme,agent:patient,patient:theme]), member(_:rel(E,X,ArgX,_),C), member(_:rel(E,Y,ArgY,_),C), noun(C,X,XX), nmod(C,X,1,XM), noun(C,Y,YY), nmod(C,Y,2,YM), emod(C,E,Mod). tuple(C,tuple([XX:1|XM],[YY:2|YM],[EE,0:ArgX:1,0:ArgY:2|Mod])):- event(C,E,EE), member(ArgX,[agent,theme,patient]), member(_:rel(E,X,ArgX,_),C), member(_:rel(E,Y,ArgY,_),C), \+ member(ArgY,[agent,theme,patient]), noun(C,X,XX), nmod(C,X,1,XM), noun(C,Y,YY), nmod(C,Y,2,YM), emod(C,E,Mod). /* ======================================================================= Concepts ======================================================================= */ noun(C,X,pred(Pred)):- member(_:pred(X,Pred,n,_),C), \+ member(Pred,[person,male,human,neuter,female,there_expl,thing]). noun(C,X,name(Pred,Type)):- member(_:named(X,Pred,Type,_),C). noun(C,X,date(D0,D1,D2,D3)):- member(_:timex(X,date(_:D0,_:D1,_:D2,_:D3)),C). event(C,E,event(Event):0):- member(_:pred(E,Event,v,_),C). /* ======================================================================= Modification ======================================================================= */ emod(C,E,Mod):- findall(mod(M):0,member(_:pred(E,M,a,_),C),Mod). nmod(C,X,N,Mod):- findall(mod(M):N,member(_:pred(X,M,a,_),C),Mod1), findall(card(Card):N,member(_:card(X,Card,_),C),Mod2), append(Mod2,Mod1,Mod).
Shuailong/CCGSupertagging
ext/candc/src/prolog/boxer/tuples.pl
Perl
mit
2,830
#!/usr/bin/perl # # Takes a JMs freeze and changes it into data::dumper format for viewing and editing. # # # Kim Brugger (06 May 2010), contact: kim.brugger@easih.ac.uk use strict; use warnings; use Data::Dumper; use Storable; my $filename = shift || die "no freeze file provided\n"; my $blob = Storable::retrieve( $filename); #print Dumper( $$blob{delete_files} ); print join("\n", @{$$blob{delete_files}})."\n";
brugger/ctru-pipeline
tools/tmpfile_from_freeze.pl
Perl
mit
425
#!/usr/bin/perl use strict; use warnings; print "\nPlease install VirtualBox first...\n\n" if system("VBoxManage -v > /dev/null 2>&1") != 0; my $vm_name; if(-e 'FagrantFile') { open(FH, '< FagrantFile'); chomp($vm_name = <FH>); close(FH); if(!vm_state($vm_name, 'exists')) { print "VM from FagrantFile doesn't exist. :x\n"; exit 1; } } my $subroutines = {'init' => \&init, 'up' => \&up, 'provision' => \&provision, 'ssh' => \&ssh, 'halt' => \&halt, 'destroy' => \&destroy}; $ARGV[0] && $ARGV[0] =~ /(init|up|provision|ssh|halt|destroy)/ ? $subroutines->{$ARGV[0]}->() : help(); sub vm_state { my ($vm_name, $state) = @_; return grep {/^"(.+)"\s{1}[^"]+$/;$vm_name eq $1} `VBoxManage list vms` if $state eq 'exists'; return grep {/^"(.+)"\s{1}[^"]+$/;$vm_name eq $1} `VBoxManage list runningvms` if $state eq 'running'; } sub init { if($vm_name) { print "Wow wow, there's already a fagrant VM for this directory?! Are you crazy?\n"; return; } if(vm_state($ARGV[1], "exists")) { $vm_name = $ARGV[1] . "_" . time(); print "Cloning VM with name '$vm_name'.\n"; print `VBoxManage clonevm $ARGV[1] --name "$vm_name"`; my $vm_directory = shift [ map {/Default machine folder:\s+(.+)$/;$1} grep {/^Default machine folder:/} `VBoxManage list systemproperties` ]; my $vm_location = $vm_directory . '/' . $vm_name . '/' . $vm_name . '.vbox'; print `VBoxManage registervm "$vm_location"`; open(FH, "> FagrantFile") and print FH $vm_name and close(FH); } else { print "Sorry, couldn't find a VM with the name '$vm_name'.\n"; } } sub up { if($vm_name) { my $port = 2000 + int(rand(1000)); `VBoxManage modifyvm "$vm_name" --natpf1 delete "guestssh" > /dev/null 2>&1`; `VBoxManage modifyvm "$vm_name" --natpf1 "guestssh,tcp,,$port,,22" > /dev/null 2>&1`; `VBoxManage sharedfolder remove "$vm_name" --name guestfolder > /dev/null 2>&1`; `VBoxManage sharedfolder add "$vm_name" --name "guestfolder" --hostpath $ENV{PWD} --automount > /dev/null 2>&1`; print "Booting VM...\n"; system("VBoxHeadless --startvm \"$vm_name\" > /dev/null 2>&1 &"); sleep(15); # Find a better way? } } sub provision { ssh("sudo mount -t vboxsf -o uid=\$(id -u),gid=\$(id -g) guestfolder /fagrant"); ssh("puppet apply /fagrant/manifests/default.pp"); } sub ssh { my $user = $ARGV[1] // "fagrant"; my $command = $_[0] // ""; my $keyfile = $user eq 'vagrant' ? $ENV{HOME} . '/.vagrant.d/insecure_private_key' : $ENV{HOME} . '/.ssh/fagrant'; my $ssh_port = shift [ map {/host port = (\d+),/;$1} grep {/NIC \d+ Rule.+guest port = 22/} `VBoxManage showvminfo "$vm_name"` ]; system("ssh -q -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -i $keyfile $user\@localhost -p $ssh_port $command") if $vm_name && vm_state($vm_name, 'running'); } sub halt { my $method = $ARGV[1] && $ARGV[1] eq '--force' ? 'poweroff' : 'acpipowerbutton'; `VBoxManage controlvm "$vm_name" $method` if $vm_name && vm_state($vm_name, 'running'); } sub destroy { if($vm_name) { halt() if vm_state($vm_name, 'running'); if(not defined $ARGV[1]) { print "Not so fast José! U sure? "; # I know myself, I need this. `VBoxManage unregistervm "$vm_name" --delete` if <STDIN> =~ /^ye?s?/i; } `VBoxManage snapshot restorecurrent "$vm_name"` if $ARGV[1] && $ARGV[1] eq '--revert'; unlink('FagrantFile'); } } sub help { print "\nFagrant - does what vagrant does, only in 100 loc.\n\n"; print "\t$0 init <VM name> - Initialize new VM in current working directory, cloned from <VM name>\n"; print "\t$0 up - Boot the VM\n"; print "\t$0 provision - Provision the VM\n"; print "\t$0 ssh <user> - SSH into the box\n"; print "\t$0 halt - Halt the VM\n"; print "\t$0 destroy - Destroy the VM\n"; print "\t$0 destroy --revert - Revert the VM to latest snapshot and remove FagrantFile\n"; print "\t$0 help - Print this\n\n"; }
xsawyerx/fagrant
fagrant.pl
Perl
mit
4,126
#! /usr/bin/perl -w package LoginApp::Model::User; use Moo; extends 'LoginApp::Model'; sub getUserByFBId { my $class = shift; my ($fbid) = @_; return $class->getDbh->resultset('User')->search({ 'fbid' => $fbid })->first; } 1;
szilardcsom/mojo_login
lib/LoginApp/Model/User.pm
Perl
mit
243
# Copyright 2020, Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. package Google::Ads::GoogleAds::V8::Resources::AdGroupAd; use strict; use warnings; use base qw(Google::Ads::GoogleAds::BaseEntity); use Google::Ads::GoogleAds::Utils::GoogleAdsHelper; sub new { my ($class, $args) = @_; my $self = { actionItems => $args->{actionItems}, ad => $args->{ad}, adGroup => $args->{adGroup}, adStrength => $args->{adStrength}, labels => $args->{labels}, policySummary => $args->{policySummary}, resourceName => $args->{resourceName}, status => $args->{status}}; # Delete the unassigned fields in this object for a more concise JSON payload remove_unassigned_fields($self, $args); bless $self, $class; return $self; } 1;
googleads/google-ads-perl
lib/Google/Ads/GoogleAds/V8/Resources/AdGroupAd.pm
Perl
apache-2.0
1,309
# # Copyright 2022 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package centreon::common::cisco::standard::snmp::mode::components::temperature; use strict; use warnings; my %map_temperature_state = ( 1 => 'normal', 2 => 'warning', 3 => 'critical', 4 => 'shutdown', 5 => 'not present', 6 => 'not functioning' ); # In MIB 'CISCO-ENVMON-MIB' my $mapping = { ciscoEnvMonTemperatureStatusDescr => { oid => '.1.3.6.1.4.1.9.9.13.1.3.1.2' }, ciscoEnvMonTemperatureStatusValue => { oid => '.1.3.6.1.4.1.9.9.13.1.3.1.3' }, ciscoEnvMonTemperatureThreshold => { oid => '.1.3.6.1.4.1.9.9.13.1.3.1.4' }, ciscoEnvMonTemperatureState => { oid => '.1.3.6.1.4.1.9.9.13.1.3.1.6', map => \%map_temperature_state } }; my $oid_ciscoEnvMonTemperatureStatusEntry = '.1.3.6.1.4.1.9.9.13.1.3.1'; sub load { my ($self) = @_; push @{$self->{request}}, { oid => $oid_ciscoEnvMonTemperatureStatusEntry }; } sub check { my ($self) = @_; $self->{output}->output_add(long_msg => "Checking temperatures"); $self->{components}->{temperature} = { name => 'temperatures', total => 0, skip => 0 }; return if ($self->check_filter(section => 'temperature')); foreach my $oid ($self->{snmp}->oid_lex_sort(keys %{$self->{results}->{$oid_ciscoEnvMonTemperatureStatusEntry}})) { next if ($oid !~ /^$mapping->{ciscoEnvMonTemperatureState}->{oid}\.(.*)$/); my $instance = $1; my $result = $self->{snmp}->map_instance(mapping => $mapping, results => $self->{results}->{$oid_ciscoEnvMonTemperatureStatusEntry}, instance => $instance); next if ($self->check_filter(section => 'temperature', instance => $instance, name => $result->{ciscoEnvMonTemperatureStatusDescr})); $self->{components}->{temperature}->{total}++; $self->{output}->output_add( long_msg => sprintf( "temperature '%s' status is %s [instance: %s] [value: %s C]", $result->{ciscoEnvMonTemperatureStatusDescr}, $result->{ciscoEnvMonTemperatureState}, $instance, defined($result->{ciscoEnvMonTemperatureStatusValue}) ? $result->{ciscoEnvMonTemperatureStatusValue} : '-' ) ); my $exit = $self->get_severity(section => 'temperature', instance => $instance, value => $result->{ciscoEnvMonTemperatureState}); if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) { $self->{output}->output_add( severity => $exit, short_msg => sprintf( "Temperature '%s' status is %s", $result->{ciscoEnvMonTemperatureStatusDescr}, $result->{ciscoEnvMonTemperatureState} ) ); } next if (!defined($result->{ciscoEnvMonTemperatureStatusValue})); my ($exit2, $warn, $crit, $checked) = $self->get_severity_numeric(section => 'temperature', instance => $instance, name => $result->{ciscoEnvMonTemperatureStatusDescr}, value => $result->{ciscoEnvMonTemperatureStatusValue}); if ($checked == 0) { my $warn_th = undef; my $crit_th = '~:' . $result->{ciscoEnvMonTemperatureThreshold}; $self->{perfdata}->threshold_validate(label => 'warning-temperature-instance-' . $instance, value => $warn_th); $self->{perfdata}->threshold_validate(label => 'critical-temperature-instance-' . $instance, value => $crit_th); $warn = $self->{perfdata}->get_perfdata_for_output(label => 'warning-temperature-instance-' . $instance); $crit = $self->{perfdata}->get_perfdata_for_output(label => 'critical-temperature-instance-' . $instance); } if (!$self->{output}->is_status(value => $exit2, compare => 'ok', litteral => 1)) { $self->{output}->output_add( severity => $exit2, short_msg => sprintf("Temperature '%s' is %s degree centigrade", $result->{ciscoEnvMonTemperatureStatusDescr}, $result->{ciscoEnvMonTemperatureStatusValue}) ); } $self->{output}->perfdata_add( label => "temp", unit => 'C', nlabel => 'hardware.temperature.celsius', instances => $result->{ciscoEnvMonTemperatureStatusDescr}, value => $result->{ciscoEnvMonTemperatureStatusValue}, warning => $warn, critical => $crit ); } } 1;
centreon/centreon-plugins
centreon/common/cisco/standard/snmp/mode/components/temperature.pm
Perl
apache-2.0
5,107
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Copyright [2016-2018] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =cut package EnsEMBL::REST::Controller::Phenotype; use Moose; use namespace::autoclean; use Try::Tiny; use Bio::EnsEMBL::Utils::Scalar qw/check_ref/; require EnsEMBL::REST; EnsEMBL::REST->turn_on_config_serialisers(__PACKAGE__); =pod /phenotype/accession/homo_sapiens/EFO_0003900 /phenotype/term/homo_sapiens/ciliopathy application/json =cut BEGIN {extends 'Catalyst::Controller::REST'; } with 'EnsEMBL::REST::Role::PostLimiter'; #/phenotype/accession/homo_sapiens/EFO_0003900 sub accession_GET {} sub accession: Chained('/') PathPart('phenotype/accession') Args(2) ActionClass('REST') { my ($self, $c, $species, $accession) = @_; my $phenotype_features; try { $phenotype_features = $c->model('Phenotype')->fetch_by_accession($species, $accession); } catch { $c->log->debug('Problems:'.$_) }; $self->status_ok($c, entity => $phenotype_features ); } #/phenotype/term/homo_sapiens/ciliopathy sub term_GET {} sub term: Chained('/') PathPart('phenotype/term') Args(2) ActionClass('REST') { my ($self, $c, $species, $term) = @_; my $phenotype_features; try { $phenotype_features = $c->model('Phenotype')->fetch_by_term($species, $term); } catch { $c->log->debug('Problems:'.$_) }; $self->status_ok($c, entity => $phenotype_features ); } =pod /phenotype/region/Homo_sapiens/X:1000000-2000000?feature_type=Variation; feature_type = The type of feature associated with phenotype to retrieve (Variation/StructuralVariation/Gene/QTL). only_phenotypes = Only returns associated phenotype description and mapped ontology accessions for a lighter output. application/json text/x-gff3 =cut has 'max_slice_length' => ( isa => 'Num', is => 'ro', default => 1e7); sub region_GET {} sub region: Chained('/') PathPart('phenotype/region') Args(2) ActionClass('REST') { my ($self, $c, $species, $region) = @_; $c->stash()->{species} = $species; # Needed to be populated for the 'Lookup' service my $features; try { my ($sr_name) = $c->model('Lookup')->decode_region( $region, 1, 1 ); my $slice = $c->model('Lookup')->find_slice($region); $self->assert_slice_length($c, $slice); $features = $c->model('Phenotype')->fetch_features_by_region($species, $slice); } catch { $c->go('ReturnError', 'from_ensembl', [qq{$_}]) if $_ =~ /STACK/; $c->go('ReturnError', 'custom', [qq{$_}]); }; $self->status_ok($c, entity => $features ); } with 'EnsEMBL::REST::Role::SliceLength'; __PACKAGE__->meta->make_immutable; 1;
helensch/ensembl-rest
lib/EnsEMBL/REST/Controller/Phenotype.pm
Perl
apache-2.0
3,212
/* XPM */ static char *logo_32x32_m[] = { /* columns rows colors chars-per-pixel */ "32 32 22 1 ", " c #00708B", ". c #00708C", "X c #01708C", "o c #00708D", "O c #00718D", "+ c #06738F", "@ c #007593", "# c #0B7690", "$ c #127892", "% c #137993", "& c #007CA0", "* c #208099", "= c #0086B0", "- c #0097CB", "; c #00AAEA", ": c #00ADEF", "> c #01ADEF", ", c #02ADEF", "< c #09AEED", "1 c #0AAEED", "2 c #00AEF0", "3 c None", /* pixels */ "33333333333333333333333333333333", "33333333333333::3333333333333333", "3333333333333:::33OO333333333333", "3333333333333::233OO333333333333", "33333333333:::333OOO333333333333", "33333333333::23 OO33333333333333", "33333333333::33OOO33333333333333", "333333333333333OOO33333333333333", "33333333333333333OOO333333333333", "33333333333333333OOO333333333333", "333333333333333333OO333333333333", "3333333OOOO333333333333333333333", "3333OOOOOOOO333::333::3333333333", "333OOOOOOOOO333::333::::33333333", "33OOOOOOOOOOOO33333::::::3333333", "33OOOOOOOOOOOOO333::::::::333333", "333OOOOOOOOOOOO333::::::::333333", "333OOOOOOOOOOOOOO333:::::::33333", "333OOOOOOOOOOOOOO333:::::::33333", "3333OOOOOOOOOOOOO333::::::::3333", "3333OOOOOOOOOOOOOO=222::::::3333", "3333OOOOOOOOOOOOOO@:22::11::3333", "33333OOOOOOOOOOOOO -2:3333333333", "33333OOOOOOOOO#33%O@:33333333333", "33333OOOOOOO3333333*333333333333", "33333OOOOOO333333333333333333333", "333333OOOO3333333333333333333333", "333333OOO33333333333333333333333", "333333OO%33333333333333333333333", "3333333+333333333333333333333333", "33333333333333333333333333333333", "33333333333333333333333333333333" };
termsuite/termsuite-ui
products/fr.univnantes.termsuite.product/img/logo-32x32.m.pm
Perl
apache-2.0
1,593
# Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute # Copyright [2016-2017] EMBL-European Bioinformatics Institute # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. package Bio::EnsEMBL::Analysis::Runnable::ProteinAnnotation::IPRScan; use warnings ; use vars qw(@ISA); use strict; # Object preamble - inherits from Bio::EnsEMBL::Root; use Bio::EnsEMBL::Analysis::Runnable::ProteinAnnotation; use Bio::EnsEMBL::Utils::Exception qw(throw warning); @ISA = qw(Bio::EnsEMBL::Analysis::Runnable::ProteinAnnotation); sub new{ my ($class, @args) = @_; my $self = $class->SUPER::new(@args); ###################### #SETTING THE DEFAULTS# ###################### $self->options('-cli -appl blastprodom -appl fprintscan -appl hmmpfam -appl superfamily -appl hmmpir -appl scanregexp -format raw') if(!$self->options); #$self->options('-cli -appl blastprodom -appl fprintscan -appl hmmpfam -appl hmmpir -appl hmmpanther -appl hmmtigr -appl hmmsmart -appl superfamily -format raw') if(!$self->options); #self->options('-cli -appl blastprodom -appl fprintscan -appl hmmpfam -appl hmmpir -appl hmmpanther -appl hmmtigr -appl hmmsmart -appl superfamily -appl gene3d -format raw') ###################### return $self; } #testing the different programs # -appl <name> Application(s) to run (optional), default is all. # Possible values (dependent on set-up): # * blastprodom # * fprintscan # 8 hmmpfam # 8 hmmpir # * hmmpanther # 8 hmmtigr # 7 hmmsmart # 8 superfamily # * gene3d # 8 scanregexp # 8 profilescan # 8 seg # 8 coils # 8 [tmhmm] # 8 [signalp] ################# sub run_analysis{ my ($self) = @_; #example command #/nfs/acari/lec/code/interpro/interpro_ftp/iprscan/bin/iprscan -cli -format raw #-i /nfs/acari/lec/code/interpro/interpro_ftp/iprscan/test.seq print "RUNNING ANALYSIS\n"; my $command = $self->program." ".$self->options." -i ".$self->queryfile. " >& ".$self->resultsfile; print "Running ".$command."\n"; throw ("Error running ".$command)unless ((system ($command)) == 0); } sub parse_results{ my ($self) = @_; print "PARSING RESULTS\n"; open(OUT, "<".$self->resultsfile) or throw("FAILED to open ". $self->resultsfile. " IPRSCAN:parse_results"); my @out; while(<OUT>){ print; chomp; if(/SUBMITTED\s+(\S+)/){ my $dir_name = $1; #print "GETTING filename HAVE ".$dir_name."\n"; #iprscan-20071115-10500980 my ($base_dir) = $dir_name =~ /iprscan\-(\d+)\-\d+/; my $full_path = $self->workdir."/".$base_dir."/".$dir_name; $self->files_to_delete($full_path); #print $full_path."\n"; next; } next if((!$_) || (!$_ =~ /\d+/)); #print $_."\n"; #19897 4AB50DD3FDE96DB6 468 ProfileScan PS50157 ZINC_FINGER_C2H2_2 243 270 16.685 T 14-Nov-2007 my ($translation_id, $crd, $aa_length, $method, $hit_name, $desc, $start, $end, $evalue, $status, $date) = split /\t/, $_; if(!$start || !$end){ next; } if($evalue && !($evalue =~ /\d+/)){ $evalue = undef; } if($start > $end){ my $temp = $start; $start = $end; $end = $temp; } my $pf = $self->create_protein_feature($start, $end, 0, $translation_id, 0, 0, $hit_name, $self->analysis, $evalue, 0); throw("Protein feature has no translation id") if(!$pf->seqname); push(@out, $pf); } $self->output(\@out); close(OUT); } #NF00181542 is the id of the input sequence. #27A9BBAC0587AB84 is the crc64 (checksum) of the protein sequence (supposed to be unique). #272 is the length of the sequence (in AA). #HMMPIR is the anaysis method launched. #PIRSF001424 is the database members entry for this match. #Prephenate dehydratase is the database member description for the entry. #1 is the start of the domain match. #270 is the end of the domain match. #6.5e-141 is the evalue of the match (reported by member database anayling method). #T is the status of the match (T: true, M: marginal). #06-Aug-2005 is the date of the run.
james-monkeyshines/ensembl-analysis
modules/Bio/EnsEMBL/Analysis/Runnable/ProteinAnnotation/IPRScan.pm
Perl
apache-2.0
5,135
package Paws::ES::DescribeElasticsearchDomainConfig; use Moose; has DomainName => (is => 'ro', isa => 'Str', traits => ['ParamInURI'], uri_name => 'DomainName', required => 1); use MooseX::ClassAttribute; class_has _api_call => (isa => 'Str', is => 'ro', default => 'DescribeElasticsearchDomainConfig'); class_has _api_uri => (isa => 'Str', is => 'ro', default => '/2015-01-01/es/domain/{DomainName}/config'); class_has _api_method => (isa => 'Str', is => 'ro', default => 'GET'); class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::ES::DescribeElasticsearchDomainConfigResponse'); class_has _result_key => (isa => 'Str', is => 'ro'); 1; ### main pod documentation begin ### =head1 NAME Paws::ES::DescribeElasticsearchDomainConfig - Arguments for method DescribeElasticsearchDomainConfig on Paws::ES =head1 DESCRIPTION This class represents the parameters used for calling the method DescribeElasticsearchDomainConfig on the Amazon Elasticsearch Service service. Use the attributes of this class as arguments to method DescribeElasticsearchDomainConfig. You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to DescribeElasticsearchDomainConfig. As an example: $service_obj->DescribeElasticsearchDomainConfig(Att1 => $value1, Att2 => $value2, ...); Values for attributes that are native types (Int, String, Float, etc) can passed as-is (scalar values). Values for complex Types (objects) can be passed as a HashRef. The keys and values of the hashref will be used to instance the underlying object. =head1 ATTRIBUTES =head2 B<REQUIRED> DomainName => Str The Elasticsearch domain that you want to get information about. =head1 SEE ALSO This class forms part of L<Paws>, documenting arguments for method DescribeElasticsearchDomainConfig in L<Paws::ES> =head1 BUGS and CONTRIBUTIONS The source code is located here: https://github.com/pplu/aws-sdk-perl Please report bugs to: https://github.com/pplu/aws-sdk-perl/issues =cut
ioanrogers/aws-sdk-perl
auto-lib/Paws/ES/DescribeElasticsearchDomainConfig.pm
Perl
apache-2.0
2,037
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =cut =head1 CONTACT Please email comments or questions to the public Ensembl developers list at <http://lists.ensembl.org/mailman/listinfo/dev>. Questions may also be sent to the Ensembl help desk at <http://www.ensembl.org/Help/Contact>. =cut package Bio::EnsEMBL::Variation::Pipeline::ProteinFunction::RunWeka; use strict; use File::Copy; use File::Path qw(make_path remove_tree); use Bio::EnsEMBL::Variation::ProteinFunctionPredictionMatrix; use base ('Bio::EnsEMBL::Variation::Pipeline::ProteinFunction::BaseProteinFunction'); sub run { my $self = shift; my $translation_md5 = $self->required_param('translation_md5'); my $feature_file = $self->required_param('feature_file'); my $pph_dir = $self->required_param('pph_dir'); my $humdiv_model = $self->required_param('humdiv_model'); my $humvar_model = $self->required_param('humvar_model'); # copy stuff to /tmp to avoid lustre slowness my ($output_dir, $feature_filename) = $feature_file =~ /(.+)\/([^\/]+)$/; my $tmp_dir = "/tmp/weka_${translation_md5}"; make_path($tmp_dir); copy($feature_file, $tmp_dir); my $input_file = "${tmp_dir}/${feature_filename}"; # unzip the file if necessary if ($input_file =~ /\.gz$/ && -e $input_file) { system("gunzip -f $input_file") == 0 or die "Failed to gunzip input file: $input_file"; } $input_file =~ s/.gz$//; chdir $output_dir or die "Failed to chdir to $output_dir"; my @to_delete; my $var_dba = $self->get_species_adaptor('variation'); my $pfpma = $var_dba->get_ProteinFunctionPredictionMatrixAdaptor or die "Failed to get matrix adaptor"; for my $model ($humdiv_model, $humvar_model) { next unless $model; my $model_name = $model eq $humdiv_model ? 'humdiv' : 'humvar'; my $output_file = "${tmp_dir}/${model_name}.txt"; my $error_file = "${model_name}.err"; my $cmd = "$pph_dir/bin/run_weka.pl -l $model $input_file 1> $output_file 2> $error_file"; system($cmd) == 0 or die "Failed to run $cmd: $?"; if (-s $error_file) { warn "run_weka.pl STDERR output in $error_file\n"; } else { push @to_delete, $error_file; } open (RESULT, "<$output_file") or die "Failed to open output file: $!"; my @fields; my $peptide = $self->get_transcript_file_adaptor->get_translation_seq($translation_md5); my $pred_matrix = Bio::EnsEMBL::Variation::ProteinFunctionPredictionMatrix->new( -analysis => 'polyphen', -sub_analysis => $model_name, -peptide_length => length($peptide), -translation_md5 => $translation_md5, ); while (<RESULT>) { if (/^#/) { s/#//g; @fields = split /\s+/; next; } die "No header line in result file $output_file?" unless @fields; my @values = split /\t/; # trim whitespace map { $_ =~ s/^\s+//; $_ =~ s/\s+$// } @values; # parse the results into a hash my %results = map { $fields[$_] => $values[$_] } (0 .. @fields-1); my $alt_aa = $results{o_aa2}; my $prediction = $results{prediction}; my $prob = $results{pph2_prob}; my $position = $results{o_pos}; next unless $position && $alt_aa; $pred_matrix->add_prediction( $position, $alt_aa, $prediction, $prob, ); } # save the predictions to the database $pfpma->store($pred_matrix); } remove_tree($tmp_dir); unlink @to_delete; } 1;
dbolser/ensembl-variation
modules/Bio/EnsEMBL/Variation/Pipeline/ProteinFunction/RunWeka.pm
Perl
apache-2.0
4,500
#!/usr/bin/env perl # Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute # Copyright [2016-2017] EMBL-European Bioinformatics Institute # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. use strict; use warnings; use Bio::AlignIO; use File::Spec; use Getopt::Long; use Bio::EnsEMBL::ApiVersion; use Bio::EnsEMBL::Registry; use Bio::EnsEMBL::Compara::DBSQL::DBAdaptor; use Bio::EnsEMBL::Compara::Graph::OrthoXMLWriter; use Bio::EnsEMBL::Compara::Graph::GeneTreePhyloXMLWriter; use Bio::EnsEMBL::Compara::Graph::CAFETreePhyloXMLWriter; use Bio::EnsEMBL::Compara::Utils::Preloader; my $tree_id_file; my $one_tree_id; my $url; my $help = 0; my $aln_out; my $fasta_out; my $fasta_cds_out; my $nh_out; my $nhx_out; my $orthoxml; my $phyloxml; my $cafe_phyloxml; my $aa = 1; my $dirpath; my $reg_conf; my $reg_alias; $| = 1; GetOptions('help' => \$help, 'tree_id_file|infile=s' => \$tree_id_file, 'tree_id=i' => \$one_tree_id, 'reg_conf=s' => \$reg_conf, 'reg_alias=s' => \$reg_alias, 'url=s' => \$url, 'a|aln_out=s' => \$aln_out, 'f|fasta_out=s' => \$fasta_out, 'fc|fasta_cds_out=s' => \$fasta_cds_out, 'nh|nh_out=s' => \$nh_out, 'nhx|nhx_out=s' => \$nhx_out, 'oxml|orthoxml=s' => \$orthoxml, 'pxml|phyloxml=s' => \$phyloxml, 'cafe|cafe_phyloxml=s' => \$cafe_phyloxml, 'aa=s' => \$aa, 'dirpath=s' => \$dirpath, ); if ($help) { print " $0 [--tree_id id | --tree_id_file file.txt] [--url mysql://ensro\@compara1:3306/kb3_ensembl_compara_59 | -reg_conf reg_file.pm -reg_alias alias ] --tree_id the root_id of the tree to be dumped --tree_id_file a file with a list of tree_ids --url string database url location of the form, mysql://username[:password]\@host[:port]/[release_version] --aa dump alignment in amino acid (default is in DNA) --dirpath where to dump the files to (default is the directory of tree_id_file) The following parameters define the data that should be dumped. string is the filename extension. If string is 1, the default extension will be used --nh_out string tree in newick / EMF format (nh.emf) --nhx_out string tree in extended newick / EMF format (nhx.emf) --aln_out string multiple alignment in EMF format (aln.emf) --fasta_out string amino-acid multiple alignment in FASTA format (aa.fasta) --fasta_cds_out string nucleotide multiple alignment in FASTA format (cds.fasta) --orthoxml string tree in OrthoXML format (orthoxml.xml) --phyloxml string tree in PhyloXML format (phyloxml.xml) --cafe_phyloxml string CAFE tree in PhyloXML format (cafe_phyloxml.xml) This scripts assumes that the compara db is linked to all the core dbs \n"; exit 0; } unless ( (defined $tree_id_file && (-r $tree_id_file)) or $one_tree_id ) { print "\n either --tree_id_file or --tree_id has to be defined.\nEXIT 1\n\n"; exit 1; } unless ($url or ($reg_conf and $reg_alias)) { print "\nNeither --url nor --reg_conf and --reg_alias is not defined. The URL should be something like mysql://ensro\@compara1:3306/kb3_ensembl_compara_59\nEXIT 2\n\n"; exit 2; } if($reg_conf) { Bio::EnsEMBL::Registry->load_all($reg_conf); # if undefined, default reg_conf will be used } my $dba = $reg_alias ? Bio::EnsEMBL::Registry->get_DBAdaptor( $reg_alias, 'compara' ) : Bio::EnsEMBL::Compara::DBSQL::DBAdaptor->new( -URL => $url ); my $adaptor = $dba->get_GeneTreeAdaptor; my @tree_ids; if($tree_id_file and -r $tree_id_file) { open LIST, '<', $tree_id_file or die "couldnt open $tree_id_file: $!\n"; @tree_ids = <LIST>; chomp @tree_ids; close LIST; } else { @tree_ids = ($one_tree_id); } unless($dirpath) { if($tree_id_file) { my ($dummy_volume, $dummy_file); ($dummy_volume, $dirpath, $dummy_file) = File::Spec->splitpath( $tree_id_file ); } else { $dirpath = '.'; } } sub dump_if_wanted { my $param = shift; return unless $param; my $tree_id = shift; my $default_name = shift; my $filename = ($param =~ /^\// ? sprintf('%s.%s', $param, $tree_id) : sprintf('%s/%s.%s', $dirpath, $tree_id, $param eq 1 ? $default_name : $param)); return if -s $filename; my $fh; open $fh, '>', $filename or die "couldnt open $filename:$!\n"; my $sub = shift; my $root = shift; my $extra = shift; &$sub($root, $fh, @$extra); close $fh; } foreach my $tree_id (@tree_ids) { system("mkdir -p $dirpath") && die "Could not make directory '$dirpath: $!"; my $tree = $adaptor->fetch_by_root_id($tree_id); my $root = $tree->root; my $cafe_tree = $dba->get_CAFEGeneFamilyAdaptor->fetch_by_GeneTree($tree); $tree_id = "tree.".$tree_id; my %fasta_names = ('protein' => 'aa.fasta', 'ncrna' => 'nt.fasta'); if ($aln_out or $nh_out or $nhx_out) { Bio::EnsEMBL::Compara::Utils::Preloader::load_all_DnaFrags($dba->get_DnaFragAdaptor, $tree->get_all_Members); } dump_if_wanted($aln_out, $tree_id, 'aln.emf', \&dumpTreeMultipleAlignment, $tree, []); dump_if_wanted($nh_out, $tree_id, 'nh.emf', \&dumpNewickTree, $root, [0]); dump_if_wanted($nhx_out, $tree_id, 'nhx.emf', \&dumpNewickTree, $root, [1]); dump_if_wanted($fasta_out, $tree_id, $fasta_names{$tree->member_type}, \&dumpTreeFasta, $root, [0]); dump_if_wanted($fasta_cds_out, $tree_id, 'cds.fasta', \&dumpTreeFasta, $root, [1]) if $tree->member_type eq 'protein'; dump_if_wanted($orthoxml, $tree_id, 'orthoxml.xml', \&dumpTreeOrthoXML, $tree); dump_if_wanted($phyloxml, $tree_id, 'phyloxml.xml', \&dumpTreePhyloXML, $tree); dump_if_wanted($cafe_phyloxml, $tree_id, 'cafe_phyloxml.xml', \&dumpCafeTreePhyloXML, $cafe_tree) if $cafe_tree; $root->release_tree; } sub dumpTreeMultipleAlignment { my $tree = shift; my $fh = shift; Bio::EnsEMBL::Compara::Utils::Preloader::load_all_sequences($dba->get_SequenceAdaptor, $aa ? undef : 'cds', $tree->get_all_Members); my @aligned_seqs; foreach my $leaf (@{$tree->get_all_leaves}) { #SEQ organism peptide_stable_id chr sequence_start sequence_stop strand gene_stable_id display_label my $species = $leaf->genome_db->name; $species =~ s/ /_/; print $fh "SEQ $species ".$leaf->stable_id." ".$leaf->dnafrag->name." ".$leaf->dnafrag_start." ".$leaf->dnafrag_end." ".$leaf->dnafrag_strand." ".$leaf->gene_member->stable_id." ".($leaf->gene_member->display_label || "NULL") ."\n"; my $alignment_string; if ($aa) { $alignment_string = $leaf->alignment_string; } else { $alignment_string = $leaf->alignment_string('cds'); } for (my $i = 0; $i<length($alignment_string); $i++) { $aligned_seqs[$i] .= substr($alignment_string, $i, 1); } } # will need to update the script when we will produce omega score for each column # of the alignment. # print "SCORE NULL\n"; # Here come the trees print $fh "TREE newick ", $tree->newick_format('simple'), "\n"; print $fh "TREE nhx ", $tree->nhx_format, "\n"; print $fh "DATA\n"; print $fh join("\n", @aligned_seqs); print $fh "\n//\n\n"; } sub dumpNewickTree { my $tree = shift; my $fh = shift; my $nhx = shift; # print STDERR "node_id: ",$tree->node_id,"\n"; my @aligned_seqs; foreach my $leaf (@{$tree->get_all_leaves}) { #SEQ organism peptide_stable_id chr sequence_start sequence_stop strand gene_stable_id display_label my $species = $leaf->genome_db->name; $species =~ s/ /_/; print $fh "SEQ $species ".$leaf->stable_id." ".$leaf->dnafrag->name." ".$leaf->dnafrag_start." ".$leaf->dnafrag_end." ".$leaf->dnafrag_strand." ".$leaf->gene_member->stable_id." ".($leaf->gene_member->display_label || "NULL") ."\n"; } # will need to update the script when we will produce omega score for each column # of the alignment. # print "SCORE NULL\n"; print $fh "DATA\n"; if ($nhx) { print $fh $tree->nhx_format; } else { print $fh $tree->newick_format('simple'); } print $fh "\n//\n\n"; } sub dumpTreeFasta { my $tree = shift; my $fh = shift; my $cdna = shift; my @aligned_seqs; warn("missing tree\n") unless($tree); my $sa; $sa = $tree->get_SimpleAlign(-id_type => 'STABLE', $cdna ? (-seq_type => 'cds') : () ); $sa->set_displayname_flat(1); my $alignIO = Bio::AlignIO->newFh(-fh => $fh, -format => 'fasta' ); print $alignIO $sa; print $fh "\n//\n\n"; } sub dumpTreeOrthoXML { my $tree = shift; my $fh = shift; my $w = Bio::EnsEMBL::Compara::Graph::OrthoXMLWriter->new(-SOURCE => 'compara', -SOURCE_VERSION => software_version(), -HANDLE => $fh, -NO_RELEASE_TREES => 1); $w->write_trees($tree); $w->finish(); } sub dumpTreePhyloXML { my $tree = shift; my $fh = shift; my $w = Bio::EnsEMBL::Compara::Graph::GeneTreePhyloXMLWriter->new(-SOURCE => 'compara', -NO_SEQUENCES => 1, -HANDLE => $fh, -NO_RELEASE_TREES => 1); $w->write_trees($tree); $w->finish(); } sub dumpCafeTreePhyloXML { my $tree = shift; my $fh = shift; my $w = Bio::EnsEMBL::Compara::Graph::CAFETreePhyloXMLWriter->new(-SOURCE => 'compara', -NO_SEQUENCES => 1, -HANDLE => $fh, -NO_RELEASE_TREES => 1); $w->write_trees($tree); $w->finish(); }
danstaines/ensembl-compara
scripts/dumps/dumpTreeMSA_id.pl
Perl
apache-2.0
9,991
# # Copyright 2022 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package hardware::server::ibm::bladecenter::snmp::mode::components::ambient; use strict; use warnings; my $oid_temperature = '.1.3.6.1.4.1.2.3.51.2.2.1'; my $oid_end = '.1.3.6.1.4.1.2.3.51.2.2.1.5'; my $oid_rearLEDCardTempMax = '.1.3.6.1.4.1.2.3.51.2.2.1.5.3.0'; # In MIB 'mmblade.mib' and 'cme.mib' my $oids = { bladecenter => { mm => '.1.3.6.1.4.1.2.3.51.2.2.1.1.2.0', frontpanel => '.1.3.6.1.4.1.2.3.51.2.2.1.5.1.0', frontpanel2 => '.1.3.6.1.4.1.2.3.51.2.2.1.5.2.0', }, pureflex => { ambient => '.1.3.6.1.4.1.2.3.51.2.2.1.5.1.0', # rearLEDCardTempAvg } }; sub load { my ($self) = @_; push @{$self->{request}}, { oid => $oid_temperature, end => $oid_end }; } sub check { my ($self) = @_; $self->{output}->output_add(long_msg => "Checking ambient"); $self->{components}->{ambient} = {name => 'ambient', total => 0, skip => 0}; return if ($self->check_filter(section => 'ambient')); my @sensors = ('mm', 'frontpanel', 'frontpanel2'); my $label = 'bladecenter'; if (defined($self->{results}->{$oid_temperature}->{$oid_rearLEDCardTempMax})) { @sensors = ('ambient'); $label = 'pureflex'; } foreach my $temp (@sensors) { if (!defined($self->{results}->{$oid_temperature}->{$oids->{$label}->{$temp}}) || $self->{results}->{$oid_temperature}->{$oids->{$label}->{$temp}} !~ /([0-9\.]+)/) { $self->{output}->output_add(long_msg => sprintf("skip ambient '%s': no values", $temp)); next; } my $value = $1; next if ($self->check_filter(section => 'ambient', instance => $temp)); $self->{components}->{ambient}->{total}++; $self->{output}->output_add(long_msg => sprintf("ambient '%s' is %s degree centigrade.", $temp, $value)); my ($exit, $warn, $crit, $checked) = $self->get_severity_numeric(section => 'ambient', instance => $temp, value => $value); if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) { $self->{output}->output_add(severity => $exit, short_msg => sprintf("ambient '%s' is %s degree centigrade", $temp, $value)); } $self->{output}->perfdata_add( label => 'temp', unit => 'C', nlabel => 'hardware.ambient.temperature.celsius', instances => $temp, value => $value, warning => $warn, critical => $crit ); } } 1;
centreon/centreon-plugins
hardware/server/ibm/bladecenter/snmp/mode/components/ambient.pm
Perl
apache-2.0
3,497
package Google::Ads::AdWords::v201402::TypeMaps::AdGroupAdService; use strict; use warnings; our $typemap_1 = { 'queryResponse/rval/entries/experimentData/experimentDeltaStatus' => 'Google::Ads::AdWords::v201402::ExperimentDeltaStatus', 'mutateResponse/rval/value/ad[ImageAd]/image/urls/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'getResponse/rval/entries/ad[TemplateAd]/adAsImage/urls' => 'Google::Ads::AdWords::v201402::Media_Size_StringMapEntry', 'queryResponse/rval/entries/ad[ThirdPartyRedirectAd]/isUserInterestTargeted' => 'SOAP::WSDL::XSD::Typelib::Builtin::boolean', 'mutateResponse/rval/partialFailureErrors' => 'Google::Ads::AdWords::v201402::ApiError', 'getResponse/rval/entries/ad[MobileAd]/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/partialFailureErrors[ClientTermsError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[RichMediaAd]/url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[ReadOnlyError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/disapprovalReasons' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[EntityCountLimitExceeded]/existingCount' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/youTubeVideoIdString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/dimensions' => 'Google::Ads::AdWords::v201402::Media_Size_DimensionsMapEntry', 'mutateResponse/rval/partialFailureErrors[RangeError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/status' => 'Google::Ads::AdWords::v201402::AdGroupAd::Status', 'mutateResponse/rval/value/ad[ImageAd]/Ad.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/urls/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'Fault/detail/ApiExceptionFault/errors[DateError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[MediaError]/reason' => 'Google::Ads::AdWords::v201402::MediaError::Reason', 'Fault/detail/ApiExceptionFault/errors[AdGroupAdCountLimitExceeded]/existingCount' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'get/serviceSelector/predicates' => 'Google::Ads::AdWords::v201402::Predicate', 'queryResponse/rval/entries/ad[TextAd]' => 'Google::Ads::AdWords::v201402::TextAd', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/dimensions' => 'Google::Ads::AdWords::v201402::Media_Size_DimensionsMapEntry', 'mutateResponse/rval/partialFailureErrors[DistinctError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/mediaId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/dimensions/value/height' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutateResponse/rval/partialFailureErrors[DateError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[ProductAd]/devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'Fault/detail/ApiExceptionFault/errors[AdGroupAdCountLimitExceeded]/reason' => 'Google::Ads::AdWords::v201402::EntityCountLimitExceeded::Reason', 'queryResponse/rval/entries/ad[TemplateAd]/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/adAsImage/creationTime' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[MobileImageAd]' => 'Google::Ads::AdWords::v201402::MobileImageAd', 'getResponse/rval/entries/ad[MobileAd]/phoneNumber' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[ReadOnlyError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia/dimensions/value/height' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutateResponse/rval/value/ad[ImageAd]/image/data' => 'SOAP::WSDL::XSD::Typelib::Builtin::base64Binary', 'getResponse/rval/entries/ad[TemplateAd]/adAsImage/dimensions/value/height' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutateResponse/rval/partialFailureErrors[ExperimentError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[ProductAd]/promotionLine' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[StatsQueryError]' => 'Google::Ads::AdWords::v201402::StatsQueryError', 'Fault/detail/ApiExceptionFault/errors[RateExceededError]/reason' => 'Google::Ads::AdWords::v201402::RateExceededError::Reason', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia/mimeType' => 'Google::Ads::AdWords::v201402::Media::MimeType', 'mutateResponse/rval/partialFailureErrors[RejectedError]' => 'Google::Ads::AdWords::v201402::RejectedError', 'mutate/operations/operand/ad[TemplateAd]/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutate/operations/operand/ad[ThirdPartyRedirectAd]/adDuration' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'Fault/detail/ApiExceptionFault/errors[AdGroupAdError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[NewEntityCreationError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/disapprovalReasons' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/advertisingId' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[MobileImageAd]/image/dimensions/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'getResponse/rval/entries/ad[ImageAd]/image/urls/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'mutateResponse/rval/partialFailureErrors[NotEmptyError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/approvalStatus' => 'Google::Ads::AdWords::v201402::AdGroupAd::ApprovalStatus', 'mutateResponse/rval/value/status' => 'Google::Ads::AdWords::v201402::AdGroupAd::Status', 'mutateResponse/rval/value/ad[TextAd]/Ad.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia/type' => 'Google::Ads::AdWords::v201402::Media::MediaType', 'getResponse/rval/entries/ad[TemplateAd]/adUnionId/AdUnionId.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[ClientTermsError]' => 'Google::Ads::AdWords::v201402::ClientTermsError', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia/type' => 'Google::Ads::AdWords::v201402::Media::MediaType', 'mutateResponse/rval/value/ad[MobileAd]/url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/dimensions' => 'Google::Ads::AdWords::v201402::Media_Size_DimensionsMapEntry', 'mutate/operations/operand/ad[ImageAd]/displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad' => 'Google::Ads::AdWords::v201402::Ad', 'ApiExceptionFault/errors/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/experimentData/experimentDeltaStatus' => 'Google::Ads::AdWords::v201402::ExperimentDeltaStatus', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/fileSize' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutate/operations/exemptionRequests' => 'Google::Ads::AdWords::v201402::ExemptionRequest', 'queryResponse/rval/entries/ad[ImageAd]/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'Fault/detail/ApiExceptionFault/errors[AdGroupAdCountLimitExceeded]' => 'Google::Ads::AdWords::v201402::AdGroupAdCountLimitExceeded', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia/sourceUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[MobileAd]/businessName' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/readyToPlayOnTheWeb' => 'SOAP::WSDL::XSD::Typelib::Builtin::boolean', 'mutate/operations/operand/ad[TemplateAd]/adAsImage/data' => 'SOAP::WSDL::XSD::Typelib::Builtin::base64Binary', 'queryResponse/rval/entries/ad[MobileImageAd]/image/dimensions' => 'Google::Ads::AdWords::v201402::Media_Size_DimensionsMapEntry', 'getResponse/rval/entries/experimentData' => 'Google::Ads::AdWords::v201402::AdGroupAdExperimentData', 'mutateResponse/rval/partialFailureErrors[SelectorError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[RichMediaAd]' => 'Google::Ads::AdWords::v201402::RichMediaAd', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/referenceId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/partialFailureErrors[AdGroupAdError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/adUnionId[TempAdUnionId]/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutate/operations/operand/ad[MobileImageAd]/devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'get/serviceSelector/predicates/operator' => 'Google::Ads::AdWords::v201402::Predicate::Operator', 'mutateResponse/rval/partialFailureErrors[RequestError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TextAd]/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'getResponse/rval/entries/ad[TemplateAd]/adUnionId[TempAdUnionId]/AdUnionId.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/urls' => 'Google::Ads::AdWords::v201402::Media_Size_StringMapEntry', 'getResponse/rval/entries/ad[ThirdPartyRedirectAd]/impressionBeaconUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TextAd]/devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutate/operations/operand/ad[ImageAd]/image/urls/value' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[RichMediaAd]/dimensions/height' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[PagingError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[MobileImageAd]/image/mimeType' => 'Google::Ads::AdWords::v201402::Media::MimeType', 'Fault/detail/ApiExceptionFault/errors[StringLengthError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/type' => 'Google::Ads::AdWords::v201402::Media::MediaType', 'Fault/detail/ApiExceptionFault/errors[PolicyViolationError]/key/violatingText' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[ImageAd]/image/dimensions' => 'Google::Ads::AdWords::v201402::Media_Size_DimensionsMapEntry', 'mutateResponse/rval/partialFailureErrors[DistinctError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]' => 'Google::Ads::AdWords::v201402::Image', 'Fault/detail/ApiExceptionFault/errors[DateError]/reason' => 'Google::Ads::AdWords::v201402::DateError::Reason', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia/Media.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[RichMediaAd]/richMediaAdType' => 'Google::Ads::AdWords::v201402::RichMediaAd::RichMediaAdType', 'mutateResponse/rval/value/ad[ImageAd]/image' => 'Google::Ads::AdWords::v201402::Image', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia/sourceUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[AdGroupAdCountLimitExceeded]/enclosingId' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[RateExceededError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[DynamicSearchAd]/displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[MobileImageAd]/image/urls/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/type' => 'Google::Ads::AdWords::v201402::Media::MediaType', 'mutateResponse/rval/partialFailureErrors/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/adAsImage/sourceUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/Media.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'get/serviceSelector/dateRange/min' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/urls/value' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/originAdId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'queryResponse/rval/entries/experimentData/experimentDataStatus' => 'Google::Ads::AdWords::v201402::ExperimentDataStatus', 'getResponse/rval/entries/ad[TemplateAd]/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'queryResponse/rval/entries/ad[MobileAd]/url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[ImageAd]/adToCopyImageFrom' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/industryStandardCommercialIdentifier' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[RequiredError]/reason' => 'Google::Ads::AdWords::v201402::RequiredError::Reason', 'mutateResponse/rval/partialFailureErrors[EntityCountLimitExceeded]/limit' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'queryResponse/rval/entries/ad[DynamicSearchAd]/description2' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[MobileImageAd]/image/dimensions/value/height' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/dimensions/value/width' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'queryResponse/rval/entries/ad[ImageAd]/image/Media.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/originAdId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia/referenceId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'Fault/detail/ApiExceptionFault/errors[StatsQueryError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[ForwardCompatibilityError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/dimensions/value' => 'Google::Ads::AdWords::v201402::Dimensions', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/urls/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'mutate/operations/operand/ad[MobileImageAd]/Ad.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[ImageAd]/image/type' => 'Google::Ads::AdWords::v201402::Media::MediaType', 'queryResponse/rval/entries/ad[TemplateAd]/adAsImage/sourceUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[SelectorError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/fileSize' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutate/operations/operand/ad[MobileImageAd]/image/urls/value' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[ThirdPartyRedirectAd]/richMediaAdType' => 'Google::Ads::AdWords::v201402::RichMediaAd::RichMediaAdType', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia/mediaId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/value/ad[TemplateAd]/adAsImage/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[MobileImageAd]/Ad.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/totalNumEntries' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'queryResponse/rval/entries/ad[ImageAd]/image/data' => 'SOAP::WSDL::XSD::Typelib::Builtin::base64Binary', 'mutateResponse/rval/partialFailureErrors[PagingError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[MobileAd]/url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[EntityCountLimitExceeded]/enclosingId' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[MediaError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]' => 'Google::Ads::AdWords::v201402::Video', 'mutate/operations/operand/experimentData/experimentId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutate/operations/operand/ad[MobileImageAd]/image/urls' => 'Google::Ads::AdWords::v201402::Media_Size_StringMapEntry', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/dimensions/value/width' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'queryResponse/rval/entries/ad[MobileImageAd]/image/referenceId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/partialFailureErrors[SelectorError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/sourceUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[DeprecatedAd]/url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[MobileAd]/description' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[NewEntityCreationError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[ThirdPartyRedirectAd]/sourceUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields' => 'Google::Ads::AdWords::v201402::TemplateElementField', 'mutate/operations/operand/ad[TemplateAd]/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[EntityCountLimitExceeded]' => 'Google::Ads::AdWords::v201402::EntityCountLimitExceeded', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/urls/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/Media.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/urls' => 'Google::Ads::AdWords::v201402::Media_Size_StringMapEntry', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/urls/value' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/advertisingId' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[MobileImageAd]/mobileCarriers' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/creationTime' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[SizeLimitError]' => 'Google::Ads::AdWords::v201402::SizeLimitError', 'getResponse/rval/entries/ad[MobileImageAd]/image/urls/value' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[DynamicSearchAd]/description2' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[ProductAd]/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'getResponse/rval/entries/ad[ProductAd]/promotionLine' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/dimensions' => 'Google::Ads::AdWords::v201402::Dimensions', 'Fault/detail/ApiExceptionFault/errors[InternalApiError]' => 'Google::Ads::AdWords::v201402::InternalApiError', 'getResponse/rval/entries/ad[ImageAd]/image/data' => 'SOAP::WSDL::XSD::Typelib::Builtin::base64Binary', 'getResponse/rval/entries/ad[ImageAd]/image/creationTime' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/creationTime' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[ImageAd]/image/creationTime' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[AuthorizationError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad/Ad.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/adUnionId[TempAdUnionId]/AdUnionId.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[ImageAd]/image/dimensions/value/height' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'queryResponse/rval/entries/forwardCompatibilityMap' => 'Google::Ads::AdWords::v201402::String_StringMapEntry', 'mutateResponse/rval/partialFailureErrors[OperationAccessDenied]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[ImageError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[PolicyViolationError]/externalPolicyUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[ThirdPartyRedirectAd]/sourceUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[PolicyViolationError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[AdGroupAdCountLimitExceeded]/existingCount' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/sourceUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/industryStandardCommercialIdentifier' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/mimeType' => 'Google::Ads::AdWords::v201402::Media::MimeType', 'queryResponse/rval/Page.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TextAd]/url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[AuthenticationError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia/dimensions/value' => 'Google::Ads::AdWords::v201402::Dimensions', 'mutate/operations/operand/ad[ThirdPartyRedirectAd]/certifiedVendorFormatId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'Fault/detail/ApiExceptionFault/errors[ForwardCompatibilityError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[MobileAd]/devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutate/operations/operand/ad[ProductAd]/url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[ThirdPartyRedirectAd]/isTagged' => 'SOAP::WSDL::XSD::Typelib::Builtin::boolean', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia/creationTime' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/approvalStatus' => 'Google::Ads::AdWords::v201402::AdGroupAd::ApprovalStatus', 'mutate/operations/operand/ad[TemplateAd]/dimensions' => 'Google::Ads::AdWords::v201402::Dimensions', 'queryResponse/rval/entries/ad[ThirdPartyRedirectAd]/adAttributes' => 'Google::Ads::AdWords::v201402::RichMediaAd::AdAttribute', 'getResponse/rval/entries/ad[RichMediaAd]/impressionBeaconUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/forwardCompatibilityMap' => 'Google::Ads::AdWords::v201402::String_StringMapEntry', 'getResponse/rval/entries/ad' => 'Google::Ads::AdWords::v201402::Ad', 'mutate/operations/operand/ad[MobileImageAd]/image/dimensions/value/width' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/Media.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[ImageAd]/image/dimensions/value/height' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'getResponse/rval/entries/ad[DeprecatedAd]' => 'Google::Ads::AdWords::v201402::DeprecatedAd', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia/mimeType' => 'Google::Ads::AdWords::v201402::Media::MimeType', 'mutateResponse/rval/partialFailureErrors[NotEmptyError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/urls/value' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[IdError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[ImageAd]/image/dimensions/value' => 'Google::Ads::AdWords::v201402::Dimensions', 'mutateResponse/rval/value/experimentData' => 'Google::Ads::AdWords::v201402::AdGroupAdExperimentData', 'mutateResponse/rval/value/ad[DynamicSearchAd]' => 'Google::Ads::AdWords::v201402::DynamicSearchAd', 'queryResponse/rval/entries/ad[DynamicSearchAd]/displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[DistinctError]/reason' => 'Google::Ads::AdWords::v201402::DistinctError::Reason', 'mutateResponse/rval/partialFailureErrors[DatabaseError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/mediaId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/value/ad[TemplateAd]/adUnionId[TempAdUnionId]' => 'Google::Ads::AdWords::v201402::TempAdUnionId', 'mutate/operations/operand/ad[MobileImageAd]/image/data' => 'SOAP::WSDL::XSD::Typelib::Builtin::base64Binary', 'getResponse/rval' => 'Google::Ads::AdWords::v201402::AdGroupAdPage', 'getResponse/rval/entries/ad[RichMediaAd]/sourceUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[RichMediaAd]/dimensions' => 'Google::Ads::AdWords::v201402::Dimensions', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[MobileImageAd]/displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[ClientTermsError]' => 'Google::Ads::AdWords::v201402::ClientTermsError', 'mutateResponse/rval/value/ad[ImageAd]/image/urls' => 'Google::Ads::AdWords::v201402::Media_Size_StringMapEntry', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/uniqueName' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/trademarkDisapproved' => 'SOAP::WSDL::XSD::Typelib::Builtin::boolean', 'getResponse/rval/entries/ad[TextAd]/Ad.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]' => 'Google::Ads::AdWords::v201402::Image', 'mutate/operations/operand/ad[DynamicSearchAd]/displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/type' => 'Google::Ads::AdWords::v201402::Media::MediaType', 'mutate/operations/operand/ad[RichMediaAd]/adAttributes' => 'Google::Ads::AdWords::v201402::RichMediaAd::AdAttribute', 'mutateResponse/rval/value/ad[TemplateAd]/adAsImage/mediaId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'Fault/detail/ApiExceptionFault/errors[AdError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[ThirdPartyRedirectAd]/certifiedVendorFormatId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'getResponse/rval/entries/ad[RichMediaAd]/dimensions/height' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/dimensions/value/height' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/advertisingId' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[ImageAd]/Ad.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[QueryError]/reason' => 'Google::Ads::AdWords::v201402::QueryError::Reason', 'mutate/operations/operand/ad[RichMediaAd]/displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/adAsImage/dimensions/value' => 'Google::Ads::AdWords::v201402::Dimensions', 'mutateResponse/rval/value/ad[MobileImageAd]/image/dimensions' => 'Google::Ads::AdWords::v201402::Media_Size_DimensionsMapEntry', 'mutateResponse/rval/value/ad[ThirdPartyRedirectAd]/Ad.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[ThirdPartyRedirectAd]/dimensions' => 'Google::Ads::AdWords::v201402::Dimensions', 'Fault/detail/ApiExceptionFault/errors[RejectedError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[ThirdPartyRedirectAd]/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[ThirdPartyRedirectAd]/impressionBeaconUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/trademarkDisapproved' => 'SOAP::WSDL::XSD::Typelib::Builtin::boolean', 'mutateResponse/rval/partialFailureErrors[DateError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/dimensions/value/height' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'getResponse/rval/entries/ad[ProductAd]/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutate/operations/operand/ad[TemplateAd]' => 'Google::Ads::AdWords::v201402::TemplateAd', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/type' => 'Google::Ads::AdWords::v201402::Media::MediaType', 'mutateResponse/rval/value/ad/url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[RejectedError]/reason' => 'Google::Ads::AdWords::v201402::RejectedError::Reason', 'mutate/operations/operand/ad[ImageAd]/image' => 'Google::Ads::AdWords::v201402::Image', 'Fault/detail/ApiExceptionFault/errors[NewEntityCreationError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[DeprecatedAd]' => 'Google::Ads::AdWords::v201402::DeprecatedAd', 'ApiExceptionFault/ApplicationException.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[RichMediaAd]/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia/fileSize' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/dimensions/value' => 'Google::Ads::AdWords::v201402::Dimensions', 'getResponse/rval/entries/ad[TemplateAd]/adAsImage/fileSize' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/value/ad[TemplateAd]/dimensions/height' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutateResponse/rval/value/ad[ThirdPartyRedirectAd]/adAttributes' => 'Google::Ads::AdWords::v201402::RichMediaAd::AdAttribute', 'mutate/operations/operand/ad[MobileImageAd]/image' => 'Google::Ads::AdWords::v201402::Image', 'getResponse/rval/entries/ad[MobileImageAd]/mobileCarriers' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[ImageAd]/image/creationTime' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[ImageAd]/devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'Fault/detail/ApiExceptionFault/errors[EntityNotFound]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[AdGroupAdCountLimitExceeded]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[ProductAd]' => 'Google::Ads::AdWords::v201402::ProductAd', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldText' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TextAd]/Ad.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/adAsImage/creationTime' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[NullError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[RichMediaAd]/richMediaAdType' => 'Google::Ads::AdWords::v201402::RichMediaAd::RichMediaAdType', 'mutateResponse/rval/partialFailureErrors[IdError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia/Media.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[DateError]/reason' => 'Google::Ads::AdWords::v201402::DateError::Reason', 'mutateResponse/rval/value/ad[TemplateAd]/adAsImage/urls/value' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/sourceUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[MobileImageAd]/markupLanguages' => 'Google::Ads::AdWords::v201402::MarkupLanguageType', 'mutateResponse/rval/value/ad[MobileImageAd]/image/urls' => 'Google::Ads::AdWords::v201402::Media_Size_StringMapEntry', 'Fault/detail/ApiExceptionFault/errors[DatabaseError]' => 'Google::Ads::AdWords::v201402::DatabaseError', 'mutate/operations/operand/ad[ImageAd]/image/sourceUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/type' => 'Google::Ads::AdWords::v201402::Media::MediaType', 'getResponse/rval/entries/ad[DeprecatedAd]/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[ImageAd]/Ad.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TextAd]/devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/partialFailureErrors[ForwardCompatibilityError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/dimensions/value' => 'Google::Ads::AdWords::v201402::Dimensions', 'getResponse/rval/entries/adGroupId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/value/ad[RichMediaAd]/certifiedVendorFormatId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/partialFailureErrors[EntityNotFound]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[RequestError]/reason' => 'Google::Ads::AdWords::v201402::RequestError::Reason', 'mutateResponse/rval/partialFailureErrors[PagingError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/fileSize' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/partialFailureErrors[QuotaCheckError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[InternalApiError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[IdError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[PagingError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[ThirdPartyRedirectAd]/Ad.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[ForwardCompatibilityError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[AdError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/adAsImage/referenceId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'getResponse/rval/entries/ad[ImageAd]/displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operator' => 'Google::Ads::AdWords::v201402::Operator', 'mutateResponse/rval/value/ad[TemplateAd]/adAsImage/type' => 'Google::Ads::AdWords::v201402::Media::MediaType', 'mutate/operations/operand/ad[DynamicSearchAd]' => 'Google::Ads::AdWords::v201402::DynamicSearchAd', 'mutateResponse/rval/value/ad[TemplateAd]/adAsImage/dimensions/value' => 'Google::Ads::AdWords::v201402::Dimensions', 'mutateResponse/rval/partialFailureErrors[AdError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[ThirdPartyRedirectAd]/sourceUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/adAsImage/dimensions/value/width' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'queryResponse/rval/entries/ad[MobileAd]/businessName' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[DistinctError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'ApiExceptionFault/message' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/adAsImage/dimensions/value/width' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/sourceUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TextAd]/headline' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[PagingError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'query' => 'Google::Ads::AdWords::v201402::AdGroupAdService::query', 'mutateResponse/rval/value/ad[ImageAd]/image/Media.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/urls' => 'Google::Ads::AdWords::v201402::Media_Size_StringMapEntry', 'mutateResponse/rval/value/ad[MobileImageAd]/image/dimensions/value/height' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'Fault/detail/ApiExceptionFault/errors[InternalApiError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[DatabaseError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[ClientTermsError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad/url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/dimensions/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'mutate/operations/operand/ad[MobileAd]/headline' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[RequiredError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/adAsImage/dimensions/value/height' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutate/operations/operand/ad[ImageAd]/image/fileSize' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/value/ad[ThirdPartyRedirectAd]/isCookieTargeted' => 'SOAP::WSDL::XSD::Typelib::Builtin::boolean', 'getResponse/rval/entries/ad[TemplateAd]/adAsImage/dimensions/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'getResponse/rval/entries/ad[ImageAd]/image/dimensions/value' => 'Google::Ads::AdWords::v201402::Dimensions', 'Fault/detail/ApiExceptionFault/errors[InternalApiError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[MobileImageAd]/image/dimensions/value/height' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia/urls' => 'Google::Ads::AdWords::v201402::Media_Size_StringMapEntry', 'mutateResponse/rval/partialFailureErrors[NotEmptyError]' => 'Google::Ads::AdWords::v201402::NotEmptyError', 'mutateResponse/rval/value/ad[RichMediaAd]/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[RequestError]' => 'Google::Ads::AdWords::v201402::RequestError', 'getResponse/rval/entries/ad[MobileImageAd]/image/dimensions' => 'Google::Ads::AdWords::v201402::Media_Size_DimensionsMapEntry', 'Fault/detail/ApiExceptionFault/errors[ForwardCompatibilityError]/reason' => 'Google::Ads::AdWords::v201402::ForwardCompatibilityError::Reason', 'queryResponse/rval/entries/experimentData' => 'Google::Ads::AdWords::v201402::AdGroupAdExperimentData', 'mutate/operations/operand/ad[RichMediaAd]/snippet' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/faultcode' => 'SOAP::WSDL::XSD::Typelib::Builtin::anyURI', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]' => 'Google::Ads::AdWords::v201402::Image', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia/dimensions/value/height' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'Fault/detail/ApiExceptionFault/errors[OperationAccessDenied]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/dimensions/value/width' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'Fault/detail/ApiExceptionFault/errors[EntityCountLimitExceeded]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[RichMediaAd]/adDuration' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/dimensions/value/width' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutateResponse/rval/value/ad[TextAd]/displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[AuthorizationError]' => 'Google::Ads::AdWords::v201402::AuthorizationError', 'mutateResponse/rval/value/ad[RichMediaAd]/sourceUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[ImageAd]/image/referenceId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/value/ad[RichMediaAd]/snippet' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/forwardCompatibilityMap/key' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/adAsImage/creationTime' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/durationMillis' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/value/ad[RichMediaAd]/dimensions' => 'Google::Ads::AdWords::v201402::Dimensions', 'Fault/detail/ApiExceptionFault/errors[QueryError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/readyToPlayOnTheWeb' => 'SOAP::WSDL::XSD::Typelib::Builtin::boolean', 'Fault/detail/ApiExceptionFault/errors[ReadOnlyError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[ImageError]' => 'Google::Ads::AdWords::v201402::ImageError', 'queryResponse/rval/entries/ad[TemplateAd]/adAsImage/mediaId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'queryResponse/rval/entries/ad/Ad.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[AdxError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/type' => 'Google::Ads::AdWords::v201402::Media::MediaType', 'mutateResponse/rval/partialFailureErrors[StringLengthError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/experimentData/experimentId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/partialFailureErrors[ImageError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[DatabaseError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[DynamicSearchAd]/description2' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[QuotaCheckError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[AdxError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[AdGroupAdCountLimitExceeded]/accountLimitType' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[DynamicSearchAd]' => 'Google::Ads::AdWords::v201402::DynamicSearchAd', 'Fault/detail/ApiExceptionFault/errors[DateError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[RichMediaAd]/Ad.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/Ad.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[ThirdPartyRedirectAd]/dimensions' => 'Google::Ads::AdWords::v201402::Dimensions', 'getResponse/rval/entries/ad[MobileImageAd]/image' => 'Google::Ads::AdWords::v201402::Image', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/sourceUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[ImageError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/forwardCompatibilityMap/value' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/mimeType' => 'Google::Ads::AdWords::v201402::Media::MimeType', 'getResponse/rval/entries/ad[DeprecatedAd]/devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/partialFailureErrors[NullError]' => 'Google::Ads::AdWords::v201402::NullError', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/mediaId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'Fault/detail/ApiExceptionFault/message' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[MobileImageAd]/url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[ReadOnlyError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'ApiExceptionFault' => 'Google::Ads::AdWords::v201402::ApiException', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/youTubeVideoIdString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[ThirdPartyRedirectAd]/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/partialFailureErrors[SelectorError]/reason' => 'Google::Ads::AdWords::v201402::SelectorError::Reason', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/dimensions/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'mutateResponse/rval/partialFailureErrors[OperationAccessDenied]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/approvalStatus' => 'Google::Ads::AdWords::v201402::AdGroupAd::ApprovalStatus', 'mutate/operations/operand/ad[ImageAd]/image/dimensions/value' => 'Google::Ads::AdWords::v201402::Dimensions', 'Fault/detail/ApiExceptionFault/errors[RangeError]/reason' => 'Google::Ads::AdWords::v201402::RangeError::Reason', 'mutate/operations/operand/ad[MobileImageAd]/image/dimensions/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/Media.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[ReadOnlyError]' => 'Google::Ads::AdWords::v201402::ReadOnlyError', 'getResponse/rval/entries/ad[TextAd]/description1' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[AdError]' => 'Google::Ads::AdWords::v201402::AdError', 'queryResponse/rval/entries/ad[ProductAd]/url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/streamingUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[MobileImageAd]/displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[MobileAd]/description' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[ImageAd]/image/fileSize' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/dimensions/value/width' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutateResponse/rval/partialFailureErrors[StatsQueryError]' => 'Google::Ads::AdWords::v201402::StatsQueryError', 'mutateResponse/rval/value/ad[RichMediaAd]/adAttributes' => 'Google::Ads::AdWords::v201402::RichMediaAd::AdAttribute', 'Fault/detail/ApiExceptionFault/errors[NotEmptyError]' => 'Google::Ads::AdWords::v201402::NotEmptyError', 'mutate/operations/operand/ad[TemplateAd]/adUnionId' => 'Google::Ads::AdWords::v201402::AdUnionId', 'getResponse/rval/entries/ad[TemplateAd]/adAsImage/type' => 'Google::Ads::AdWords::v201402::Media::MediaType', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/creationTime' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/adAsImage/sourceUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/forwardCompatibilityMap/value' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[ImageAd]/image/type' => 'Google::Ads::AdWords::v201402::Media::MediaType', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia' => 'Google::Ads::AdWords::v201402::Media', 'mutateResponse/rval/value/ad[ThirdPartyRedirectAd]/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/partialFailureErrors[NullError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[MediaError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[MobileImageAd]/devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'Fault/detail/ApiExceptionFault/errors[QueryError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/urls/value' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[RichMediaAd]/dimensions' => 'Google::Ads::AdWords::v201402::Dimensions', 'mutate/operations/operand/ad[TextAd]/description2' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[QuotaCheckError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[RichMediaAd]/devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/partialFailureErrors/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[ThirdPartyRedirectAd]/isTagged' => 'SOAP::WSDL::XSD::Typelib::Builtin::boolean', 'mutateResponse/rval/partialFailureErrors[RejectedError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[MobileImageAd]/image/creationTime' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/experimentData/experimentDeltaStatus' => 'Google::Ads::AdWords::v201402::ExperimentDeltaStatus', 'mutate/operations/operand/ad[MobileAd]' => 'Google::Ads::AdWords::v201402::MobileAd', 'getResponse/rval/entries/ad[DynamicSearchAd]/description1' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia/dimensions' => 'Google::Ads::AdWords::v201402::Media_Size_DimensionsMapEntry', 'getResponse/rval/entries/ad[DynamicSearchAd]/devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'queryResponse/rval/entries/ad[ThirdPartyRedirectAd]/isCookieTargeted' => 'SOAP::WSDL::XSD::Typelib::Builtin::boolean', 'getResponse/rval/Page.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/dimensions/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'mutate/operations/operand/ad[ThirdPartyRedirectAd]/impressionBeaconUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/readyToPlayOnTheWeb' => 'SOAP::WSDL::XSD::Typelib::Builtin::boolean', 'Fault/detail/ApiExceptionFault/errors[EntityNotFound]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/urls/value' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/referenceId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutate/operations/operand/ad[ThirdPartyRedirectAd]/url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[AuthenticationError]/reason' => 'Google::Ads::AdWords::v201402::AuthenticationError::Reason', 'mutateResponse/rval/partialFailureErrors[RateExceededError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[AdError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[ProductAd]/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/value/ad/displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/urls/value' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[RangeError]' => 'Google::Ads::AdWords::v201402::RangeError', 'getResponse/rval/entries/ad[TextAd]' => 'Google::Ads::AdWords::v201402::TextAd', 'mutateResponse/rval/partialFailureErrors[IdError]/reason' => 'Google::Ads::AdWords::v201402::IdError::Reason', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia/type' => 'Google::Ads::AdWords::v201402::Media::MediaType', 'mutate/operations/Operation.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/mimeType' => 'Google::Ads::AdWords::v201402::Media::MimeType', 'mutate/operations/operand/ad[DeprecatedAd]/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia/dimensions/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'mutateResponse/rval/value/ad[TemplateAd]/adUnionId/AdUnionId.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[MobileImageAd]/image/sourceUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[StatsQueryError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[RichMediaAd]/dimensions/height' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'queryResponse/rval/entries/ad[DynamicSearchAd]/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/dimensions/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'Fault/detail/ApiExceptionFault/errors[OperationAccessDenied]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TextAd]/description1' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[AdxError]' => 'Google::Ads::AdWords::v201402::AdxError', 'queryResponse/rval/entries/ad[ImageAd]/image/urls' => 'Google::Ads::AdWords::v201402::Media_Size_StringMapEntry', 'mutateResponse/rval/value/ad[MobileImageAd]/image/creationTime' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'queryResponse/rval/entries/ad[ThirdPartyRedirectAd]/dimensions/width' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutateResponse/rval/partialFailureErrors[AdGroupAdError]' => 'Google::Ads::AdWords::v201402::AdGroupAdError', 'Fault/detail/ApiExceptionFault/errors[RateExceededError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[MobileImageAd]/image/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[ThirdPartyRedirectAd]/videoTypes' => 'Google::Ads::AdWords::v201402::VideoType', 'Fault/detail/ApiExceptionFault/errors[IdError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[ThirdPartyRedirectAd]/richMediaAdType' => 'Google::Ads::AdWords::v201402::RichMediaAd::RichMediaAdType', 'Fault/detail/ApiExceptionFault/errors[InternalApiError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[RangeError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[ThirdPartyRedirectAd]/displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/adAsImage/Media.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[IdError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/referenceId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'getResponse/rval/entries/ad[ImageAd]/image/dimensions/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/dimensions/value/height' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutateResponse/rval/value/ad[TemplateAd]/templateId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'getResponse/rval/entries/ad[DeprecatedAd]/url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[MobileAd]' => 'Google::Ads::AdWords::v201402::MobileAd', 'mutate/operations/operand/ad[MobileImageAd]/image/dimensions' => 'Google::Ads::AdWords::v201402::Media_Size_DimensionsMapEntry', 'getResponse/rval/entries/ad[TemplateAd]/dimensions/width' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'getResponse/rval/entries/ad[ThirdPartyRedirectAd]/devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutate/operations/operand/ad[TemplateAd]/dimensions/width' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/fileSize' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutate/operations/operand/ad[DeprecatedAd]/displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[RichMediaAd]/dimensions' => 'Google::Ads::AdWords::v201402::Dimensions', 'getResponse/rval/entries/ad[ThirdPartyRedirectAd]/expandingDirections' => 'Google::Ads::AdWords::v201402::ThirdPartyRedirectAd::ExpandingDirection', 'queryResponse/rval/entries/ad[ImageAd]/image/referenceId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/mimeType' => 'Google::Ads::AdWords::v201402::Media::MimeType', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/mimeType' => 'Google::Ads::AdWords::v201402::Media::MimeType', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia/fileSize' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutate/operations/operand/ad[TextAd]/displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/dimensions/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/sourceUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[NewEntityCreationError]' => 'Google::Ads::AdWords::v201402::NewEntityCreationError', 'mutateResponse/rval/value/ad[ThirdPartyRedirectAd]/isUserInterestTargeted' => 'SOAP::WSDL::XSD::Typelib::Builtin::boolean', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/creationTime' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/dimensions' => 'Google::Ads::AdWords::v201402::Media_Size_DimensionsMapEntry', 'get/serviceSelector/dateRange' => 'Google::Ads::AdWords::v201402::DateRange', 'get/serviceSelector/ordering/sortOrder' => 'Google::Ads::AdWords::v201402::SortOrder', 'mutateResponse/rval/value/ad[ImageAd]/image/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad/displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[IdError]' => 'Google::Ads::AdWords::v201402::IdError', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldText' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia/Media.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/dimensions/value' => 'Google::Ads::AdWords::v201402::Dimensions', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/durationMillis' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'get' => 'Google::Ads::AdWords::v201402::AdGroupAdService::get', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/dimensions/value/width' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'queryResponse/rval/entries/ad[TextAd]/displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[ProductAd]/displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/adAsImage/fileSize' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/partialFailureErrors[ReadOnlyError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[DeprecatedAd]/displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[DeprecatedAd]/Ad.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[MobileAd]/markupLanguages' => 'Google::Ads::AdWords::v201402::MarkupLanguageType', 'Fault/detail/ApiExceptionFault/errors[RequestError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[MediaError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[PolicyViolationError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[QuotaCheckError]' => 'Google::Ads::AdWords::v201402::QuotaCheckError', 'getResponse/rval/entries/ad[DynamicSearchAd]/description2' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[RateExceededError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia/dimensions/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'mutateResponse/rval/value/ad[DynamicSearchAd]/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/value/ad[ImageAd]/image/referenceId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'queryResponse/rval/entries/ad[DynamicSearchAd]/Ad.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/industryStandardCommercialIdentifier' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/fileSize' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/value/experimentData/experimentDataStatus' => 'Google::Ads::AdWords::v201402::ExperimentDataStatus', 'mutate/operations/operand/ad[TemplateAd]/adAsImage/mediaId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutate/operations/operand/ad[MobileAd]/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutate/operations/operand/ad[TemplateAd]/adAsImage/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[ThirdPartyRedirectAd]/dimensions/height' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'Fault/detail/ApiExceptionFault/errors[SelectorError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/forwardCompatibilityMap/key' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TextAd]/headline' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[MobileImageAd]/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/value/ad[DynamicSearchAd]/Ad.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[RichMediaAd]' => 'Google::Ads::AdWords::v201402::RichMediaAd', 'queryResponse/rval/entries/ad[TemplateAd]' => 'Google::Ads::AdWords::v201402::TemplateAd', 'mutateResponse/rval/partialFailureErrors[QueryError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[MobileAd]/mobileCarriers' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[RichMediaAd]/certifiedVendorFormatId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'Fault/detail/ApiExceptionFault/errors[AdGroupAdCountLimitExceeded]/limit' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutateResponse/rval/value/ad[ImageAd]/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutate/operations/exemptionRequests/key/policyName' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[SizeLimitError]/reason' => 'Google::Ads::AdWords::v201402::SizeLimitError::Reason', 'mutateResponse/rval/partialFailureErrors[RequiredError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[PolicyViolationError]/violatingParts' => 'Google::Ads::AdWords::v201402::PolicyViolationError::Part', 'getResponse/rval/entries/ad[RichMediaAd]/snippet' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[StringLengthError]' => 'Google::Ads::AdWords::v201402::StringLengthError', 'getResponse/rval/entries/forwardCompatibilityMap/value' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[AuthenticationError]/reason' => 'Google::Ads::AdWords::v201402::AuthenticationError::Reason', 'queryResponse/rval/entries/ad[RichMediaAd]/Ad.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[RichMediaAd]/displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/templateId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/value/ad[MobileImageAd]/displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/adAsImage/referenceId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'getResponse/rval/entries/ad[TemplateAd]/dimensions' => 'Google::Ads::AdWords::v201402::Dimensions', 'Fault/detail/ApiExceptionFault/errors[PolicyViolationError]/violatingParts/index' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutateResponse/rval/value/ad/devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutate/operations/operand/ad[TemplateAd]/adAsImage/mimeType' => 'Google::Ads::AdWords::v201402::Media::MimeType', 'queryResponse/rval/entries/ad[ThirdPartyRedirectAd]/certifiedVendorFormatId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'queryResponse/rval/entries/ad[RichMediaAd]/sourceUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/dimensions/value' => 'Google::Ads::AdWords::v201402::Dimensions', 'mutateResponse/rval/partialFailureErrors[RangeError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[MobileImageAd]/image/dimensions/value/width' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'Fault/detail/ApiExceptionFault/errors[MediaError]' => 'Google::Ads::AdWords::v201402::MediaError', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/mimeType' => 'Google::Ads::AdWords::v201402::Media::MimeType', 'Fault/detail/ApiExceptionFault/errors[QueryError]/reason' => 'Google::Ads::AdWords::v201402::QueryError::Reason', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/referenceId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/dimensions' => 'Google::Ads::AdWords::v201402::Media_Size_DimensionsMapEntry', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/mimeType' => 'Google::Ads::AdWords::v201402::Media::MimeType', 'queryResponse/rval/entries/ad[RichMediaAd]/displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[PolicyViolationError]/externalPolicyUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[ThirdPartyRedirectAd]/adAttributes' => 'Google::Ads::AdWords::v201402::RichMediaAd::AdAttribute', 'getResponse/rval/entries/ad[TemplateAd]/adAsImage/urls/value' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/status' => 'Google::Ads::AdWords::v201402::AdGroupAd::Status', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldText' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[RichMediaAd]/dimensions/height' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutateResponse/rval/partialFailureErrors[EntityNotFound]/reason' => 'Google::Ads::AdWords::v201402::EntityNotFound::Reason', 'Fault/detail/ApiExceptionFault/errors[DistinctError]/reason' => 'Google::Ads::AdWords::v201402::DistinctError::Reason', 'mutateResponse/rval/partialFailureErrors[MediaError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[RateExceededError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/adAsImage/mimeType' => 'Google::Ads::AdWords::v201402::Media::MimeType', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/fileSize' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutate/operations/operand/ad[TemplateAd]/originAdId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'getResponse/rval/entries/ad[MobileImageAd]/image/type' => 'Google::Ads::AdWords::v201402::Media::MediaType', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/streamingUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[PagingError]' => 'Google::Ads::AdWords::v201402::PagingError', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/fileSize' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/dimensions/value/width' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutateResponse/rval/partialFailureErrors[OperationAccessDenied]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/mediaId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'getResponse/rval/entries/ad[ThirdPartyRedirectAd]' => 'Google::Ads::AdWords::v201402::RichMediaAd', 'getResponse/rval/entries/ad[TextAd]/displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[ThirdPartyRedirectAd]/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[RejectedError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/type' => 'Google::Ads::AdWords::v201402::Media::MediaType', 'mutateResponse/rval/value/ad[ThirdPartyRedirectAd]/url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/mediaId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'getResponse/rval/entries/ad[MobileImageAd]/image/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[ClientTermsError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[ProductAd]/promotionLine' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/dimensions/value' => 'Google::Ads::AdWords::v201402::Dimensions', 'queryResponse/rval/entries/ad[TemplateAd]/adUnionId[TempAdUnionId]/AdUnionId.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[AdGroupAdError]/reason' => 'Google::Ads::AdWords::v201402::AdGroupAdError::Reason', 'mutateResponse/rval/partialFailureErrors[PolicyViolationError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[ForwardCompatibilityError]' => 'Google::Ads::AdWords::v201402::ForwardCompatibilityError', 'Fault/detail/ApiExceptionFault/errors[NullError]' => 'Google::Ads::AdWords::v201402::NullError', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/urls' => 'Google::Ads::AdWords::v201402::Media_Size_StringMapEntry', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia/urls/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'Fault/detail/ApiExceptionFault/errors[AdGroupAdError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[AdxError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[ImageAd]/displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[PolicyViolationError]/externalPolicyName' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/referenceId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia/urls' => 'Google::Ads::AdWords::v201402::Media_Size_StringMapEntry', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/fileSize' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'ApiExceptionFault/errors/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[StatsQueryError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[MobileImageAd]/image/urls' => 'Google::Ads::AdWords::v201402::Media_Size_StringMapEntry', 'Fault/detail/ApiExceptionFault/errors[MediaError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[MobileImageAd]/image/Media.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[ThirdPartyRedirectAd]/richMediaAdType' => 'Google::Ads::AdWords::v201402::RichMediaAd::RichMediaAdType', 'queryResponse/rval' => 'Google::Ads::AdWords::v201402::AdGroupAdPage', 'mutateResponse/rval/value/ad[MobileImageAd]/image/mimeType' => 'Google::Ads::AdWords::v201402::Media::MimeType', 'getResponse/rval/entries/ad[MobileImageAd]/image/fileSize' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'queryResponse/rval/entries/ad[TemplateAd]/adUnionId' => 'Google::Ads::AdWords::v201402::AdUnionId', 'Fault/detail/ApiExceptionFault/errors[ExperimentError]/reason' => 'Google::Ads::AdWords::v201402::ExperimentError::Reason', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/urls/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'queryResponse/rval/entries/ad[ImageAd]/image/dimensions/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/mimeType' => 'Google::Ads::AdWords::v201402::Media::MimeType', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/creationTime' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'ApiExceptionFault/errors/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/urls/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'queryResponse/rval/entries/ad[DeprecatedAd]/displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[AuthenticationError]' => 'Google::Ads::AdWords::v201402::AuthenticationError', 'mutate/operations/operand/ad[ImageAd]/image/mediaId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/urls/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'mutateResponse/rval/partialFailureErrors[NotEmptyError]/reason' => 'Google::Ads::AdWords::v201402::NotEmptyError::Reason', 'mutateResponse/rval/partialFailureErrors/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/adAsImage' => 'Google::Ads::AdWords::v201402::Image', 'getResponse/rval/entries/ad[TemplateAd]/displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[QuotaCheckError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[MobileAd]/phoneNumber' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/type' => 'Google::Ads::AdWords::v201402::Media::MediaType', 'mutateResponse/rval/partialFailureErrors[AdGroupAdCountLimitExceeded]/enclosingId' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/mimeType' => 'Google::Ads::AdWords::v201402::Media::MimeType', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/type' => 'Google::Ads::AdWords::v201402::Media::MediaType', 'mutateResponse/rval/partialFailureErrors[AdGroupAdCountLimitExceeded]' => 'Google::Ads::AdWords::v201402::EntityCountLimitExceeded', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[PagingError]' => 'Google::Ads::AdWords::v201402::PagingError', 'mutateResponse/rval/partialFailureErrors[IdError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia/dimensions/value' => 'Google::Ads::AdWords::v201402::Dimensions', 'getResponse/rval/entries/ad[ThirdPartyRedirectAd]/dimensions' => 'Google::Ads::AdWords::v201402::Dimensions', 'mutateResponse/rval/value/ad[MobileImageAd]/devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/partialFailureErrors[NewEntityCreationError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[EntityCountLimitExceeded]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[MobileImageAd]/mobileCarriers' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[MobileAd]/countryCode' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[RangeError]' => 'Google::Ads::AdWords::v201402::RangeError', 'Fault/detail/ApiExceptionFault/errors[RateExceededError]/retryAfterSeconds' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutateResponse/rval/partialFailureErrors[AuthenticationError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[MobileImageAd]/image/mediaId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/sourceUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[DateError]' => 'Google::Ads::AdWords::v201402::DateError', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields' => 'Google::Ads::AdWords::v201402::TemplateElementField', 'mutateResponse/rval/partialFailureErrors[PolicyViolationError]/key' => 'Google::Ads::AdWords::v201402::PolicyViolationKey', 'queryResponse/rval/entries/ad[RichMediaAd]/certifiedVendorFormatId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'queryResponse/rval/entries/ad[ImageAd]/adToCopyImageFrom' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/value/ad[ImageAd]/image/dimensions/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'mutateResponse/rval/value/ad[ImageAd]/image/dimensions/value' => 'Google::Ads::AdWords::v201402::Dimensions', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/sourceUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/type' => 'Google::Ads::AdWords::v201402::Media::MediaType', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/dimensions' => 'Google::Ads::AdWords::v201402::Media_Size_DimensionsMapEntry', 'Fault/detail/ApiExceptionFault/errors[AuthorizationError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/creationTime' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TextAd]/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/value/ad/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'getResponse/rval/entries/ad[MobileImageAd]/image/dimensions/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'mutateResponse/rval/value/ad[TemplateAd]/adAsImage/urls/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'getResponse/rval/entries/ad[TextAd]/description2' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia/dimensions/value/width' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia/urls/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/data' => 'SOAP::WSDL::XSD::Typelib::Builtin::base64Binary', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]' => 'Google::Ads::AdWords::v201402::Image', 'mutate/operations/operand/ad[ImageAd]/image/dimensions/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'Fault/detail/ApiExceptionFault/errors[RequiredError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[MediaError]' => 'Google::Ads::AdWords::v201402::MediaError', 'queryResponse/rval/entries/ad[TemplateAd]/adAsImage/Media.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[NullError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/ApplicationException.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'get/serviceSelector/ordering/field' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/adAsImage/dimensions/value/width' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'Fault/detail/ApiExceptionFault/errors[EntityCountLimitExceeded]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/creationTime' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'get/serviceSelector/fields' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/mediaId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/durationMillis' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'queryResponse/rval/entries/ad[ImageAd]/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[MobileImageAd]/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia/mediaId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/referenceId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/value/ad[TextAd]' => 'Google::Ads::AdWords::v201402::TextAd', 'Fault/detail/ApiExceptionFault/errors[ExperimentError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[EntityNotFound]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[RichMediaAd]/adDuration' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia/mediaId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutate/operations/operand/ad[TemplateAd]/adAsImage/urls' => 'Google::Ads::AdWords::v201402::Media_Size_StringMapEntry', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/sourceUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/faultactor' => 'SOAP::WSDL::XSD::Typelib::Builtin::token', 'ApiExceptionFault/errors' => 'Google::Ads::AdWords::v201402::ApiError', 'mutate/operations/operand/ad[DeprecatedAd]/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[EntityNotFound]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/adUnionId[TempAdUnionId]/AdUnionId.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[PolicyViolationError]' => 'Google::Ads::AdWords::v201402::PolicyViolationError', 'mutate' => 'Google::Ads::AdWords::v201402::AdGroupAdService::mutate', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields' => 'Google::Ads::AdWords::v201402::TemplateElementField', 'mutateResponse/rval/partialFailureErrors[QuotaCheckError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[DynamicSearchAd]' => 'Google::Ads::AdWords::v201402::DynamicSearchAd', 'getResponse/rval/entries/ad[ImageAd]/image/urls' => 'Google::Ads::AdWords::v201402::Media_Size_StringMapEntry', 'mutateResponse/rval/value/ad[TemplateAd]/adAsImage/data' => 'SOAP::WSDL::XSD::Typelib::Builtin::base64Binary', 'Fault/detail/ApiExceptionFault/errors[QueryError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/adAsImage/sourceUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/adAsImage' => 'Google::Ads::AdWords::v201402::Image', 'mutateResponse/rval/value/ad[TemplateAd]/adAsImage/urls' => 'Google::Ads::AdWords::v201402::Media_Size_StringMapEntry', 'queryResponse/rval/entries/ad[MobileAd]/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutate/operations/operand/ad[ProductAd]/devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/partialFailureErrors[RejectedError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[NullError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldText' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad/Ad.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[ThirdPartyRedirectAd]/snippet' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[MobileImageAd]' => 'Google::Ads::AdWords::v201402::MobileImageAd', 'Fault/detail/ApiExceptionFault/errors[AdError]/reason' => 'Google::Ads::AdWords::v201402::AdError::Reason', 'queryResponse/rval/entries/ad[MobileAd]/mobileCarriers' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[SizeLimitError]/reason' => 'Google::Ads::AdWords::v201402::SizeLimitError::Reason', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia/creationTime' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/referenceId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/mimeType' => 'Google::Ads::AdWords::v201402::Media::MimeType', 'getResponse/rval/entries/ad[ProductAd]/displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[DeprecatedAd]/type' => 'Google::Ads::AdWords::v201402::DeprecatedAd::Type', 'mutateResponse/rval/partialFailureErrors[QueryError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TextAd]' => 'Google::Ads::AdWords::v201402::TextAd', 'getResponse/rval/entries/ad[TemplateAd]/adUnionId[TempAdUnionId]/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/streamingUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[MobileImageAd]/image/urls/value' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/sourceUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[AdGroupAdError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/exemptionRequests/key/violatingText' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/partialFailureErrors[EntityCountLimitExceeded]' => 'Google::Ads::AdWords::v201402::EntityCountLimitExceeded', 'getResponse/rval/entries/ad[RichMediaAd]/Ad.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[ImageAd]/image/urls' => 'Google::Ads::AdWords::v201402::Media_Size_StringMapEntry', 'Fault/detail/ApiExceptionFault/errors[DistinctError]' => 'Google::Ads::AdWords::v201402::DistinctError', 'mutateResponse/rval/partialFailureErrors[NullError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[SelectorError]' => 'Google::Ads::AdWords::v201402::SelectorError', 'Fault/detail/ApiExceptionFault/errors[ReadOnlyError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[MobileAd]/markupLanguages' => 'Google::Ads::AdWords::v201402::MarkupLanguageType', 'mutateResponse/rval/value/ad[TemplateAd]' => 'Google::Ads::AdWords::v201402::TemplateAd', 'queryResponse/rval/entries/ad[TemplateAd]/duration' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutateResponse/rval/partialFailureErrors[OperationAccessDenied]/reason' => 'Google::Ads::AdWords::v201402::OperationAccessDenied::Reason', 'getResponse/rval/entries/ad[MobileAd]/description' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/experimentData/experimentId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/value/ad[RichMediaAd]/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutate/operations/operand/ad[ImageAd]/image/dimensions/value/width' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia/dimensions/value/width' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'getResponse/rval/entries/ad[ThirdPartyRedirectAd]/isUserInterestTargeted' => 'SOAP::WSDL::XSD::Typelib::Builtin::boolean', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/durationMillis' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/Media.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[IdError]' => 'Google::Ads::AdWords::v201402::IdError', 'queryResponse/rval/entries/ad[DynamicSearchAd]/devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/value/ad[MobileAd]' => 'Google::Ads::AdWords::v201402::MobileAd', 'get/serviceSelector/predicates/field' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[ThirdPartyRedirectAd]/devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'queryResponse/rval/entries/ad[ImageAd]/image/mediaId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/value/ad[MobileImageAd]/url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[StringLengthError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[RichMediaAd]/richMediaAdType' => 'Google::Ads::AdWords::v201402::RichMediaAd::RichMediaAdType', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/dimensions/value' => 'Google::Ads::AdWords::v201402::Dimensions', 'mutateResponse/rval/partialFailureErrors[RequiredError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[ThirdPartyRedirectAd]/expandingDirections' => 'Google::Ads::AdWords::v201402::ThirdPartyRedirectAd::ExpandingDirection', 'mutateResponse/rval' => 'Google::Ads::AdWords::v201402::AdGroupAdReturnValue', 'queryResponse/rval/entries/trademarkDisapproved' => 'SOAP::WSDL::XSD::Typelib::Builtin::boolean', 'queryResponse/rval/entries/ad/devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'getResponse/rval/entries/ad[RichMediaAd]/certifiedVendorFormatId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'getResponse/rval/entries/ad[DeprecatedAd]/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'Fault/detail/ApiExceptionFault/errors[OperationAccessDenied]/reason' => 'Google::Ads::AdWords::v201402::OperationAccessDenied::Reason', 'mutateResponse/rval/partialFailureErrors[DatabaseError]' => 'Google::Ads::AdWords::v201402::DatabaseError', 'mutateResponse/rval/value/ad[RichMediaAd]/dimensions/width' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'queryResponse/rval/entries/ad[ImageAd]/image/sourceUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[MobileImageAd]/markupLanguages' => 'Google::Ads::AdWords::v201402::MarkupLanguageType', 'Fault/detail/ApiExceptionFault/errors[EntityCountLimitExceeded]/enclosingId' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[NotEmptyError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[ThirdPartyRedirectAd]/richMediaAdType' => 'Google::Ads::AdWords::v201402::RichMediaAd::RichMediaAdType', 'mutate/operations/operand/experimentData/experimentDeltaStatus' => 'Google::Ads::AdWords::v201402::ExperimentDeltaStatus', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/mediaId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/partialFailureErrors[AuthorizationError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/adUnionId[TempAdUnionId]/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/value/ad[DeprecatedAd]/type' => 'Google::Ads::AdWords::v201402::DeprecatedAd::Type', 'queryResponse/rval/entries/ad[MobileImageAd]/image/mimeType' => 'Google::Ads::AdWords::v201402::Media::MimeType', 'getResponse/rval/entries/ad[ImageAd]/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/fileSize' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutate/operations/operand/ad[MobileImageAd]/markupLanguages' => 'Google::Ads::AdWords::v201402::MarkupLanguageType', 'mutateResponse/rval/value/ad[TemplateAd]/devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/type' => 'Google::Ads::AdWords::v201402::TemplateElementField::Type', 'mutateResponse/rval/value/ad[MobileAd]/countryCode' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[ImageAd]/devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'queryResponse/rval/entries/ad[DeprecatedAd]/devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/partialFailureErrors[NewEntityCreationError]/reason' => 'Google::Ads::AdWords::v201402::NewEntityCreationError::Reason', 'get/serviceSelector' => 'Google::Ads::AdWords::v201402::Selector', 'Fault/detail/ApiExceptionFault/errors[AdGroupAdCountLimitExceeded]/accountLimitType' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[ImageAd]/image/mimeType' => 'Google::Ads::AdWords::v201402::Media::MimeType', 'mutateResponse/rval/partialFailureErrors[DistinctError]' => 'Google::Ads::AdWords::v201402::DistinctError', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/Media.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[PagingError]/reason' => 'Google::Ads::AdWords::v201402::PagingError::Reason', 'Fault/detail/ApiExceptionFault/errors[RateExceededError]/rateName' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia/dimensions/value/width' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'getResponse/rval/entries/ad/devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutate/operations/operand/ad[TemplateAd]/adUnionId[TempAdUnionId]' => 'Google::Ads::AdWords::v201402::TempAdUnionId', 'Fault/detail/ApiExceptionFault/errors[SelectorError]' => 'Google::Ads::AdWords::v201402::SelectorError', 'mutateResponse/rval/value/ad[MobileAd]/devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'Fault/detail/ApiExceptionFault/errors[EntityNotFound]/reason' => 'Google::Ads::AdWords::v201402::EntityNotFound::Reason', 'getResponse/rval/entries/ad[ProductAd]/url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[AdxError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/adAsImage/mimeType' => 'Google::Ads::AdWords::v201402::Media::MimeType', 'mutateResponse/rval/partialFailureErrors[ReadOnlyError]' => 'Google::Ads::AdWords::v201402::ReadOnlyError', 'Fault/detail/ApiExceptionFault/errors[DateError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[ClientTermsError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/adUnionId[TempAdUnionId]' => 'Google::Ads::AdWords::v201402::TempAdUnionId', 'mutate/operations/operand/ad' => 'Google::Ads::AdWords::v201402::Ad', 'mutate/operations/operand/ad[ImageAd]/url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[ExperimentError]/reason' => 'Google::Ads::AdWords::v201402::ExperimentError::Reason', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/dimensions/value/height' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'getResponse/rval/entries/ad/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/partialFailureErrors[AdxError]' => 'Google::Ads::AdWords::v201402::AdxError', 'queryResponse/rval/entries/ad[TemplateAd]/Ad.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[AdError]/reason' => 'Google::Ads::AdWords::v201402::AdError::Reason', 'mutateResponse/rval/partialFailureErrors[PolicyViolationError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/urls/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia/urls/value' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[ImageAd]/image/mimeType' => 'Google::Ads::AdWords::v201402::Media::MimeType', 'queryResponse/rval/entries/ad[ImageAd]/image/creationTime' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/adAsImage/mimeType' => 'Google::Ads::AdWords::v201402::Media::MimeType', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/urls/value' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[PolicyViolationError]/key' => 'Google::Ads::AdWords::v201402::PolicyViolationKey', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia/mimeType' => 'Google::Ads::AdWords::v201402::Media::MimeType', 'mutate/operations/operand/disapprovalReasons' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[StatsQueryError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[NotEmptyError]/reason' => 'Google::Ads::AdWords::v201402::NotEmptyError::Reason', 'mutateResponse/rval/value/ad[MobileImageAd]/image/data' => 'SOAP::WSDL::XSD::Typelib::Builtin::base64Binary', 'getResponse/rval/entries/ad[ProductAd]/devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]' => 'Google::Ads::AdWords::v201402::Audio', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia/dimensions' => 'Google::Ads::AdWords::v201402::Media_Size_DimensionsMapEntry', 'queryResponse/rval/entries/ad[TemplateAd]/adAsImage/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[NullError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/dimensions' => 'Google::Ads::AdWords::v201402::Media_Size_DimensionsMapEntry', 'mutate/operations/operand/ad[RichMediaAd]/sourceUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[MobileImageAd]/image/Media.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/fileSize' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutate/operations/operand/ad[DeprecatedAd]/type' => 'Google::Ads::AdWords::v201402::DeprecatedAd::Type', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia/urls' => 'Google::Ads::AdWords::v201402::Media_Size_StringMapEntry', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/dimensions/value/width' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'getResponse/rval/entries/ad[TemplateAd]/adAsImage/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[ThirdPartyRedirectAd]/adDuration' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutateResponse/rval/partialFailureErrors[RateExceededError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/dimensions/height' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[AdGroupAdCountLimitExceeded]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[ForwardCompatibilityError]' => 'Google::Ads::AdWords::v201402::ForwardCompatibilityError', 'getResponse/rval/entries/ad[ThirdPartyRedirectAd]/certifiedVendorFormatId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'Fault/detail/ApiExceptionFault/errors[AdError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[AuthorizationError]/reason' => 'Google::Ads::AdWords::v201402::AuthorizationError::Reason', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/streamingUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'get/serviceSelector/paging' => 'Google::Ads::AdWords::v201402::Paging', 'Fault/detail/ApiExceptionFault/errors[EntityCountLimitExceeded]/limit' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'Fault/detail/ApiExceptionFault/errors[RequestError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[RichMediaAd]/devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'Fault/detail/ApiExceptionFault/errors[NewEntityCreationError]' => 'Google::Ads::AdWords::v201402::NewEntityCreationError', 'queryResponse/rval/entries/ad[TemplateAd]/adUnionId/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/mediaId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia/mediaId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/partialFailureErrors[AdGroupAdCountLimitExceeded]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[RateExceededError]/rateScope' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries' => 'Google::Ads::AdWords::v201402::AdGroupAd', 'mutateResponse/rval/value/ad[DeprecatedAd]/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[EntityNotFound]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[QueryError]/message' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[EntityNotFound]' => 'Google::Ads::AdWords::v201402::EntityNotFound', 'getResponse/rval/entries/ad[MobileImageAd]/image/mediaId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/value/ad[ThirdPartyRedirectAd]/adDuration' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/data' => 'SOAP::WSDL::XSD::Typelib::Builtin::base64Binary', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/referenceId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/partialFailureErrors[RateExceededError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[EntityCountLimitExceeded]/accountLimitType' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[PolicyViolationError]' => 'Google::Ads::AdWords::v201402::PolicyViolationError', 'Fault/detail/ApiExceptionFault/errors[SizeLimitError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia/urls/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'queryResponse/rval/entries/ad[MobileImageAd]/image/Media.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[StatsQueryError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[AdGroupAdCountLimitExceeded]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]' => 'Google::Ads::AdWords::v201402::Audio', 'mutate/operations/operand/ad[RichMediaAd]/dimensions/width' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'getResponse/rval/entries/ad[TemplateAd]/adUnionId/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/dimensions/value/height' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/referenceId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/urls/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'mutate/operations/operand/ad[TemplateAd]/adAsImage/fileSize' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/readyToPlayOnTheWeb' => 'SOAP::WSDL::XSD::Typelib::Builtin::boolean', 'Fault/detail/ApiExceptionFault/errors[NullError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[SelectorError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[ImageAd]/image/Media.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/adAsImage/mediaId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'Fault/detail/ApiExceptionFault/errors[SizeLimitError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[ProductAd]/displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[EntityNotFound]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[ThirdPartyRedirectAd]/isUserInterestTargeted' => 'SOAP::WSDL::XSD::Typelib::Builtin::boolean', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/type' => 'Google::Ads::AdWords::v201402::TemplateElementField::Type', 'getResponse/rval/entries/ad/Ad.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/dimensions' => 'Google::Ads::AdWords::v201402::Media_Size_DimensionsMapEntry', 'Fault/detail/ApiExceptionFault/errors[DateError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/urls/value' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[MobileImageAd]' => 'Google::Ads::AdWords::v201402::MobileImageAd', 'Fault/detail/ApiExceptionFault/errors[OperationAccessDenied]' => 'Google::Ads::AdWords::v201402::OperationAccessDenied', 'queryResponse/rval/entries/ad[ThirdPartyRedirectAd]/expandingDirections' => 'Google::Ads::AdWords::v201402::ThirdPartyRedirectAd::ExpandingDirection', 'mutateResponse/rval/partialFailureErrors[IdError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[ThirdPartyRedirectAd]/url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[EntityCountLimitExceeded]/accountLimitType' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[StatsQueryError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[ImageAd]/image/data' => 'SOAP::WSDL::XSD::Typelib::Builtin::base64Binary', 'Fault/detail/ApiExceptionFault/errors[QueryError]' => 'Google::Ads::AdWords::v201402::QueryError', 'mutate/operations/operand/ad[TemplateAd]/adAsImage/referenceId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/partialFailureErrors[AuthenticationError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[RateExceededError]' => 'Google::Ads::AdWords::v201402::RateExceededError', 'mutateResponse/rval/partialFailureErrors[StringLengthError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[RequestError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[EntityCountLimitExceeded]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[DistinctError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[SizeLimitError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[ThirdPartyRedirectAd]/dimensions/height' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutateResponse/rval/value/ad[ThirdPartyRedirectAd]/videoTypes' => 'Google::Ads::AdWords::v201402::VideoType', 'queryResponse/rval/entries/ad[MobileAd]/countryCode' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[RejectedError]/reason' => 'Google::Ads::AdWords::v201402::RejectedError::Reason', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/dimensions/value/height' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia/urls/value' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[RateExceededError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/adAsImage/data' => 'SOAP::WSDL::XSD::Typelib::Builtin::base64Binary', 'queryResponse/rval/entries/ad/displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'ApiExceptionFault/errors/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[PagingError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[RejectedError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[ClientTermsError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[ThirdPartyRedirectAd]/displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia/dimensions/value/height' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'Fault/detail/ApiExceptionFault/errors[ImageError]' => 'Google::Ads::AdWords::v201402::ImageError', 'mutateResponse/rval/value/ad[ThirdPartyRedirectAd]/snippet' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/readyToPlayOnTheWeb' => 'SOAP::WSDL::XSD::Typelib::Builtin::boolean', 'getResponse/rval/entries/ad[ImageAd]/Ad.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[ThirdPartyRedirectAd]/dimensions/width' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'queryResponse/rval/entries/ad[DynamicSearchAd]/url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/dimensions/value/width' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'getResponse/rval/entries/ad[MobileAd]/headline' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/type' => 'Google::Ads::AdWords::v201402::Media::MediaType', 'queryResponse/rval/entries/ad[TextAd]/Ad.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[StringLengthError]/reason' => 'Google::Ads::AdWords::v201402::StringLengthError::Reason', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[PolicyViolationError]/key/policyName' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[StatsQueryError]/reason' => 'Google::Ads::AdWords::v201402::StatsQueryError::Reason', 'mutateResponse/rval/partialFailureErrors[ImageError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/faultstring' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[ImageAd]/image/type' => 'Google::Ads::AdWords::v201402::Media::MediaType', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[DeprecatedAd]' => 'Google::Ads::AdWords::v201402::DeprecatedAd', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/creationTime' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[ExperimentError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[ForwardCompatibilityError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[ImageAd]/image/dimensions' => 'Google::Ads::AdWords::v201402::Media_Size_DimensionsMapEntry', 'mutateResponse/rval/value/ad[RichMediaAd]/displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia/creationTime' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TextAd]/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/referenceId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutate/operations/operand/ad[DynamicSearchAd]/url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/adAsImage/referenceId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'getResponse/rval/entries/ad[TemplateAd]/adAsImage/dimensions/value' => 'Google::Ads::AdWords::v201402::Dimensions', 'mutateResponse/rval/partialFailureErrors[InternalApiError]/reason' => 'Google::Ads::AdWords::v201402::InternalApiError::Reason', 'mutateResponse/rval/partialFailureErrors[AuthorizationError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[MobileAd]/mobileCarriers' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[DynamicSearchAd]/devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'Fault/detail/ApiExceptionFault/errors[QuotaCheckError]/reason' => 'Google::Ads::AdWords::v201402::QuotaCheckError::Reason', 'getResponse/rval/entries/ad[ProductAd]' => 'Google::Ads::AdWords::v201402::ProductAd', 'Fault/detail/ApiExceptionFault/errors[DatabaseError]/reason' => 'Google::Ads::AdWords::v201402::DatabaseError::Reason', 'mutate/operations/operand/ad[ThirdPartyRedirectAd]/dimensions/width' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/urls/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'mutateResponse/rval/partialFailureErrors[MediaError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[MobileImageAd]/image/fileSize' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/value/ad[RichMediaAd]/devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'Fault/detail/ApiExceptionFault/errors[DateError]' => 'Google::Ads::AdWords::v201402::DateError', 'Fault/detail/ApiExceptionFault/errors[ClientTermsError]/reason' => 'Google::Ads::AdWords::v201402::ClientTermsError::Reason', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]' => 'Google::Ads::AdWords::v201402::Audio', 'mutateResponse/rval/partialFailureErrors[NullError]/reason' => 'Google::Ads::AdWords::v201402::NullError::Reason', 'Fault/detail/ApiExceptionFault/errors[QueryError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[AuthenticationError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[MobileImageAd]/image/mimeType' => 'Google::Ads::AdWords::v201402::Media::MimeType', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/mimeType' => 'Google::Ads::AdWords::v201402::Media::MimeType', 'mutateResponse/rval/partialFailureErrors[AdGroupAdError]/reason' => 'Google::Ads::AdWords::v201402::AdGroupAdError::Reason', 'mutateResponse/rval/partialFailureErrors[QueryError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/adUnionId' => 'Google::Ads::AdWords::v201402::AdUnionId', 'Fault/detail/ApiExceptionFault/errors[ForwardCompatibilityError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia/referenceId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia/sourceUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[ImageAd]/image/mediaId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/value/ad[DeprecatedAd]/devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'queryResponse/rval/entries/ad[TemplateAd]/templateId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'queryResponse/rval/entries/ad[DeprecatedAd]/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'Fault/detail/ApiExceptionFault/errors[PolicyViolationError]/violatingParts/length' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'queryResponse/rval/entries/ad[TextAd]/description1' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[ExperimentError]' => 'Google::Ads::AdWords::v201402::ExperimentError', 'queryResponse/rval/entries/ad[ProductAd]/promotionLine' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/mediaId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/uniqueName' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/dimensions/value/height' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutate/operations/operand/ad[RichMediaAd]/impressionBeaconUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[SizeLimitError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[DeprecatedAd]/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[RangeError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[ThirdPartyRedirectAd]/snippet' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[ProductAd]/displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse' => 'Google::Ads::AdWords::v201402::AdGroupAdService::getResponse', 'mutate/operations/operand/ad[ImageAd]' => 'Google::Ads::AdWords::v201402::ImageAd', 'queryResponse/rval/entries/ad[TemplateAd]/adAsImage/urls/value' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[MobileImageAd]/image/dimensions/value' => 'Google::Ads::AdWords::v201402::Dimensions', 'mutateResponse/rval/value/ad[TextAd]/description1' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[StatsQueryError]/reason' => 'Google::Ads::AdWords::v201402::StatsQueryError::Reason', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/dimensions/value/width' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutate/operations/operand/experimentData' => 'Google::Ads::AdWords::v201402::AdGroupAdExperimentData', 'mutateResponse/rval/partialFailureErrors[DatabaseError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[RejectedError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/dimensions/value' => 'Google::Ads::AdWords::v201402::Dimensions', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/readyToPlayOnTheWeb' => 'SOAP::WSDL::XSD::Typelib::Builtin::boolean', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/dimensions/value/width' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'getResponse/rval/entries/ad[TemplateAd]/duration' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'Fault/detail/ApiExceptionFault/errors[AdGroupAdError]' => 'Google::Ads::AdWords::v201402::AdGroupAdError', 'mutateResponse/rval/partialFailureErrors[ForwardCompatibilityError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[EntityNotFound]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/forwardCompatibilityMap/key' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[MobileImageAd]/image/urls/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'mutate/operations/operand/ad[ThirdPartyRedirectAd]/displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[AuthorizationError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[MobileImageAd]/image/sourceUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[DatabaseError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia/dimensions' => 'Google::Ads::AdWords::v201402::Media_Size_DimensionsMapEntry', 'mutateResponse/rval/value/ad[DynamicSearchAd]/description1' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia/Media.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/dimensions/height' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/urls/value' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[DynamicSearchAd]/description1' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[PolicyViolationError]/violatingParts' => 'Google::Ads::AdWords::v201402::PolicyViolationError::Part', 'mutate/operations/operand/ad[ThirdPartyRedirectAd]/Ad.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[PolicyViolationError]/violatingParts/length' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'Fault/detail/ApiExceptionFault/errors[ClientTermsError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/adGroupId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/partialFailureErrors[AuthorizationError]/reason' => 'Google::Ads::AdWords::v201402::AuthorizationError::Reason', 'Fault/detail/ApiExceptionFault/errors[ClientTermsError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[RequiredError]' => 'Google::Ads::AdWords::v201402::RequiredError', 'queryResponse/rval/entries' => 'Google::Ads::AdWords::v201402::AdGroupAd', 'mutateResponse/rval/partialFailureErrors[PolicyViolationError]/isExemptable' => 'SOAP::WSDL::XSD::Typelib::Builtin::boolean', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/urls' => 'Google::Ads::AdWords::v201402::Media_Size_StringMapEntry', 'mutateResponse/rval/partialFailureErrors[RateExceededError]' => 'Google::Ads::AdWords::v201402::RateExceededError', 'mutateResponse/rval/value/ad[TemplateAd]/duration' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'Fault/detail/ApiExceptionFault/errors[InternalApiError]/reason' => 'Google::Ads::AdWords::v201402::InternalApiError::Reason', 'getResponse/rval/entries/ad[TemplateAd]/url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TextAd]/url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad/displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[AdGroupAdCountLimitExceeded]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[AuthorizationError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/Media.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[QuotaCheckError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'get/serviceSelector/predicates/values' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[OperationAccessDenied]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[MobileAd]/description' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[DeprecatedAd]/devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'getResponse/rval/entries/ad[MobileAd]/Ad.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[ImageAd]/image/Media.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/templateElements' => 'Google::Ads::AdWords::v201402::TemplateElement', 'Fault/detail/ApiExceptionFault/errors[DistinctError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[DynamicSearchAd]/description1' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]' => 'Google::Ads::AdWords::v201402::Video', 'Fault/detail/ApiExceptionFault/errors[StringLengthError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[DynamicSearchAd]/devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'Fault/detail/ApiExceptionFault/errors[SelectorError]/reason' => 'Google::Ads::AdWords::v201402::SelectorError::Reason', 'mutateResponse/rval/value/trademarkDisapproved' => 'SOAP::WSDL::XSD::Typelib::Builtin::boolean', 'getResponse/rval/entries/ad[MobileImageAd]/displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[MobileImageAd]/image/referenceId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'queryResponse/rval/entries/ad[MobileImageAd]/image/data' => 'SOAP::WSDL::XSD::Typelib::Builtin::base64Binary', 'getResponse/rval/entries/ad[TemplateAd]' => 'Google::Ads::AdWords::v201402::TemplateAd', 'mutate/operations/operand/ad[TemplateAd]/adAsImage/urls/value' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[AuthorizationError]' => 'Google::Ads::AdWords::v201402::AuthorizationError', 'mutateResponse/rval/partialFailureErrors[PagingError]/reason' => 'Google::Ads::AdWords::v201402::PagingError::Reason', 'getResponse/rval/entries/ad[ThirdPartyRedirectAd]/Ad.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[ImageAd]/adToCopyImageFrom' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'getResponse/rval/entries/ad[ImageAd]/image' => 'Google::Ads::AdWords::v201402::Image', 'mutate/operations/operand/ad[DynamicSearchAd]/Ad.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[ImageError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/experimentData/experimentDataStatus' => 'Google::Ads::AdWords::v201402::ExperimentDataStatus', 'queryResponse/rval/entries/ad[MobileAd]' => 'Google::Ads::AdWords::v201402::MobileAd', 'Fault/detail/ApiExceptionFault/errors[RequiredError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'get/serviceSelector/dateRange/max' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[ThirdPartyRedirectAd]/videoTypes' => 'Google::Ads::AdWords::v201402::VideoType', 'getResponse/rval/entries/ad[MobileAd]/devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/type' => 'Google::Ads::AdWords::v201402::TemplateElementField::Type', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/dimensions/value/height' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutateResponse/rval/partialFailureErrors[AdxError]/reason' => 'Google::Ads::AdWords::v201402::AdxError::Reason', 'queryResponse/rval/entries/ad[ImageAd]/image/mimeType' => 'Google::Ads::AdWords::v201402::Media::MimeType', 'mutate/operations/operand/ad[DeprecatedAd]/Ad.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[ThirdPartyRedirectAd]' => 'Google::Ads::AdWords::v201402::RichMediaAd', 'queryResponse/rval/entries/ad[MobileImageAd]/mobileCarriers' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[MobileImageAd]/image' => 'Google::Ads::AdWords::v201402::Image', 'mutateResponse/rval/partialFailureErrors[PolicyViolationError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[ExperimentError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[SizeLimitError]' => 'Google::Ads::AdWords::v201402::SizeLimitError', 'mutateResponse/rval/value/ad[MobileAd]/Ad.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[ThirdPartyRedirectAd]/snippet' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[QueryError]/message' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/Media.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/templateElements' => 'Google::Ads::AdWords::v201402::TemplateElement', 'queryResponse/rval/entries/experimentData/experimentId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/partialFailureErrors[DistinctError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[NewEntityCreationError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[ThirdPartyRedirectAd]/isCookieTargeted' => 'SOAP::WSDL::XSD::Typelib::Builtin::boolean', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements' => 'Google::Ads::AdWords::v201402::TemplateElement', 'Fault/detail/ApiExceptionFault/errors[NewEntityCreationError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad/devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'queryResponse/rval/entries/ad[MobileAd]/displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/dimensions/width' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'queryResponse/rval/entries/ad[RichMediaAd]/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[MobileImageAd]/image/dimensions/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'mutate/operations/operand/ad[TemplateAd]/adUnionId/AdUnionId.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia/fileSize' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'getResponse/rval/entries/ad[ImageAd]/image/fileSize' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutate/operations/operand/ad[ImageAd]/image/dimensions' => 'Google::Ads::AdWords::v201402::Media_Size_DimensionsMapEntry', 'mutateResponse/rval/partialFailureErrors/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/advertisingId' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[MobileAd]/businessName' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[ImageAd]/url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[MobileImageAd]/image/Media.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/dimensions/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'queryResponse/rval/entries/ad[DeprecatedAd]/Ad.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/adUnionId/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'queryResponse' => 'Google::Ads::AdWords::v201402::AdGroupAdService::queryResponse', 'mutateResponse/rval/partialFailureErrors[OperationAccessDenied]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[NewEntityCreationError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/creationTime' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/industryStandardCommercialIdentifier' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/dimensions/value/width' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'Fault/detail/ApiExceptionFault/errors[EntityCountLimitExceeded]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[ProductAd]/devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/dimensions' => 'Google::Ads::AdWords::v201402::Media_Size_DimensionsMapEntry', 'Fault/detail/ApiExceptionFault/errors[AdGroupAdError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[ImageAd]/url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[RateExceededError]/retryAfterSeconds' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/Media.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/status' => 'Google::Ads::AdWords::v201402::AdGroupAd::Status', 'queryResponse/rval/entries/ad[TemplateAd]/adAsImage/urls/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'mutateResponse/rval/value/ad[TemplateAd]/adAsImage/Media.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[NewEntityCreationError]/reason' => 'Google::Ads::AdWords::v201402::NewEntityCreationError::Reason', 'mutateResponse/rval/partialFailureErrors[RangeError]/reason' => 'Google::Ads::AdWords::v201402::RangeError::Reason', 'mutate/operations/operand/ad[MobileImageAd]/image/dimensions/value/height' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutateResponse/rval/partialFailureErrors[ReadOnlyError]/reason' => 'Google::Ads::AdWords::v201402::ReadOnlyError::Reason', 'mutateResponse/rval/partialFailureErrors[SizeLimitError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[ImageError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[ImageAd]/image/mimeType' => 'Google::Ads::AdWords::v201402::Media::MimeType', 'queryResponse/rval/entries/ad[ImageAd]/image/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[ProductAd]/Ad.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TextAd]/url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[SelectorError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[PolicyViolationError]/externalPolicyName' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[ReadOnlyError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[DatabaseError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[MobileImageAd]/image/referenceId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/data' => 'SOAP::WSDL::XSD::Typelib::Builtin::base64Binary', 'queryResponse/rval/entries/ad[MobileImageAd]/image/urls/value' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[ForwardCompatibilityError]/reason' => 'Google::Ads::AdWords::v201402::ForwardCompatibilityError::Reason', 'mutateResponse/rval/partialFailureErrors[AdGroupAdCountLimitExceeded]/limit' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia/sourceUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail' => 'Google::Ads::AdWords::FaultDetail', 'mutateResponse/rval/value/ad[MobileImageAd]/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'queryResponse/rval/entries/ad[MobileImageAd]/url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[ImageAd]/displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/originAdId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutate/operations/operand/ad[RichMediaAd]/adDuration' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutateResponse/rval/value/ad[MobileAd]/displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[StringLengthError]' => 'Google::Ads::AdWords::v201402::StringLengthError', 'mutateResponse/rval/partialFailureErrors[RequiredError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[ImageAd]/image/sourceUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[RequiredError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[ImageAd]/image/urls/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'mutateResponse/rval/value/ad[ThirdPartyRedirectAd]/dimensions/height' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutateResponse/rval/partialFailureErrors[RangeError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[MobileImageAd]/image/dimensions/value' => 'Google::Ads::AdWords::v201402::Dimensions', 'Fault/detail/ApiExceptionFault/errors[MediaError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[MobileAd]/displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/urls' => 'Google::Ads::AdWords::v201402::Media_Size_StringMapEntry', 'queryResponse/rval/entries/ad[DeprecatedAd]/url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/readyToPlayOnTheWeb' => 'SOAP::WSDL::XSD::Typelib::Builtin::boolean', 'Fault/detail/ApiExceptionFault/errors[RequestError]' => 'Google::Ads::AdWords::v201402::RequestError', 'getResponse/rval/entries/experimentData/experimentDataStatus' => 'Google::Ads::AdWords::v201402::ExperimentDataStatus', 'queryResponse/rval/entries/ad[ImageAd]/image/urls/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'mutate/operations/operand/ad[ThirdPartyRedirectAd]/devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'Fault/detail/ApiExceptionFault/errors[RequiredError]' => 'Google::Ads::AdWords::v201402::RequiredError', 'queryResponse/rval/entries/ad[MobileImageAd]/image/sourceUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/durationMillis' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[ImageAd]/adToCopyImageFrom' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/value/ad[MobileImageAd]/image' => 'Google::Ads::AdWords::v201402::Image', 'get/serviceSelector/paging/numberResults' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutate/operations/operand/ad[RichMediaAd]/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'Fault/detail/ApiExceptionFault/errors[AuthenticationError]' => 'Google::Ads::AdWords::v201402::AuthenticationError', 'mutate/operations/operand/ad[TemplateAd]/templateElements/uniqueName' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[MobileAd]/headline' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[NotEmptyError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[SizeLimitError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[RichMediaAd]/richMediaAdType' => 'Google::Ads::AdWords::v201402::RichMediaAd::RichMediaAdType', 'mutate/operations/operand/ad[TemplateAd]/adAsImage/dimensions/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'queryResponse/rval/entries/ad[TemplateAd]/adAsImage/fileSize' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/value/ad[TemplateAd]/displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[RichMediaAd]/adAttributes' => 'Google::Ads::AdWords::v201402::RichMediaAd::AdAttribute', 'mutate/operations/operand/ad[ThirdPartyRedirectAd]' => 'Google::Ads::AdWords::v201402::RichMediaAd', 'mutateResponse/rval/partialFailureErrors[PolicyViolationError]/violatingParts/index' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutateResponse/rval/value/forwardCompatibilityMap/value' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/adAsImage/dimensions' => 'Google::Ads::AdWords::v201402::Media_Size_DimensionsMapEntry', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/adAsImage/dimensions' => 'Google::Ads::AdWords::v201402::Media_Size_DimensionsMapEntry', 'Fault/detail/ApiExceptionFault/errors[SelectorError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/dimensions/value' => 'Google::Ads::AdWords::v201402::Dimensions', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/dimensions/value/height' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutateResponse/rval/value/ad[MobileImageAd]/image/mediaId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/partialFailureErrors[NotEmptyError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[EntityCountLimitExceeded]/reason' => 'Google::Ads::AdWords::v201402::EntityCountLimitExceeded::Reason', 'getResponse/rval/entries/ad[ThirdPartyRedirectAd]/url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[ThirdPartyRedirectAd]/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[PolicyViolationError]/externalPolicyDescription' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/disapprovalReasons' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[RangeError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[RequestError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[MobileAd]/countryCode' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[AuthorizationError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[ProductAd]/Ad.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[QueryError]' => 'Google::Ads::AdWords::v201402::QueryError', 'getResponse/rval/entries/ad[TextAd]/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/value/ad[ImageAd]/image/sourceUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[OperationAccessDenied]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[ProductAd]' => 'Google::Ads::AdWords::v201402::ProductAd', 'Fault/detail/ApiExceptionFault/errors[RateExceededError]/rateScope' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia/fileSize' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'getResponse/rval/entries/ad[ThirdPartyRedirectAd]/adDuration' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'Fault/detail/ApiExceptionFault/errors[StringLengthError]/reason' => 'Google::Ads::AdWords::v201402::StringLengthError::Reason', 'Fault/detail/ApiExceptionFault/errors[AdError]' => 'Google::Ads::AdWords::v201402::AdError', 'mutate/operations/operand/ad[TextAd]/devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse' => 'Google::Ads::AdWords::v201402::AdGroupAdService::mutateResponse', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/dimensions/value/height' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields' => 'Google::Ads::AdWords::v201402::TemplateElementField', 'mutate/operations/operand/ad[MobileImageAd]/url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/sourceUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[RichMediaAd]/dimensions/width' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'getResponse/rval/entries/ad[ImageAd]/image/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[ImageAd]/devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/partialFailureErrors[ExperimentError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[DynamicSearchAd]/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/dimensions/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'mutate/operations/operand/ad[TemplateAd]/adAsImage/dimensions/value/height' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/urls/value' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[DatabaseError]/reason' => 'Google::Ads::AdWords::v201402::DatabaseError::Reason', 'mutateResponse/rval/value/ad[TextAd]/url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/durationMillis' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'queryResponse/rval/entries/ad[MobileImageAd]/image/urls' => 'Google::Ads::AdWords::v201402::Media_Size_StringMapEntry', 'queryResponse/rval/entries/ad[MobileImageAd]/image/type' => 'Google::Ads::AdWords::v201402::Media::MediaType', 'getResponse/rval/entries/ad[MobileImageAd]/markupLanguages' => 'Google::Ads::AdWords::v201402::MarkupLanguageType', 'Fault/detail/ApiExceptionFault/errors[EntityCountLimitExceeded]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/type' => 'Google::Ads::AdWords::v201402::Media::MediaType', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/urls/value' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[RequestError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[AdxError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[OperationAccessDenied]' => 'Google::Ads::AdWords::v201402::OperationAccessDenied', 'Fault/detail/ApiExceptionFault/errors[PolicyViolationError]/key/policyName' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/streamingUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/adAsImage' => 'Google::Ads::AdWords::v201402::Image', 'queryResponse/rval/entries/ad[RichMediaAd]' => 'Google::Ads::AdWords::v201402::RichMediaAd', 'queryResponse/rval/entries/ad[MobileImageAd]/image/fileSize' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'queryResponse/rval/entries/ad[MobileAd]/Ad.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/adAsImage/dimensions' => 'Google::Ads::AdWords::v201402::Media_Size_DimensionsMapEntry', 'mutate/operations/operand/ad[ThirdPartyRedirectAd]/sourceUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/adAsImage/urls/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'queryResponse/rval/entries/ad[ThirdPartyRedirectAd]/videoTypes' => 'Google::Ads::AdWords::v201402::VideoType', 'getResponse/rval/entries/ad[RichMediaAd]/adAttributes' => 'Google::Ads::AdWords::v201402::RichMediaAd::AdAttribute', 'getResponse/rval/entries/ad[ImageAd]' => 'Google::Ads::AdWords::v201402::ImageAd', 'queryResponse/rval/entries/ad[RichMediaAd]/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/value/ad[ProductAd]/url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia/dimensions/value/height' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutate/operations/operand/ad[ThirdPartyRedirectAd]/isTagged' => 'SOAP::WSDL::XSD::Typelib::Builtin::boolean', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia/dimensions' => 'Google::Ads::AdWords::v201402::Media_Size_DimensionsMapEntry', 'mutateResponse/rval/value/ad[ImageAd]/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[EntityCountLimitExceeded]/reason' => 'Google::Ads::AdWords::v201402::EntityCountLimitExceeded::Reason', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/creationTime' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[MobileAd]/markupLanguages' => 'Google::Ads::AdWords::v201402::MarkupLanguageType', 'mutateResponse/rval/value/ad[TemplateAd]/adAsImage/dimensions' => 'Google::Ads::AdWords::v201402::Media_Size_DimensionsMapEntry', 'mutateResponse/rval/partialFailureErrors[StringLengthError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]' => 'Google::Ads::AdWords::v201402::Video', 'mutate/operations/operand/ad[ThirdPartyRedirectAd]/expandingDirections' => 'Google::Ads::AdWords::v201402::ThirdPartyRedirectAd::ExpandingDirection', 'getResponse/rval/entries/ad[MobileImageAd]/image/creationTime' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/adAsImage/creationTime' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/adUnionId[TempAdUnionId]' => 'Google::Ads::AdWords::v201402::TempAdUnionId', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/youTubeVideoIdString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[NullError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/urls' => 'Google::Ads::AdWords::v201402::Media_Size_StringMapEntry', 'Fault/detail/ApiExceptionFault/errors[NotEmptyError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[ProductAd]/Ad.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/data' => 'SOAP::WSDL::XSD::Typelib::Builtin::base64Binary', 'mutate/operations/operand/ad[TemplateAd]/displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault' => 'SOAP::WSDL::SOAP::Typelib::Fault11', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements' => 'Google::Ads::AdWords::v201402::TemplateElement', 'mutate/operations/operand/ad[RichMediaAd]/Ad.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/templateId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/uniqueName' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[ImageAd]' => 'Google::Ads::AdWords::v201402::ImageAd', 'mutate/operations/operand/ad[ThirdPartyRedirectAd]/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'Fault/detail/ApiExceptionFault/errors[AuthenticationError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[MobileAd]/Ad.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/adAsImage/dimensions/value/width' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutateResponse/rval/value/ad[ImageAd]' => 'Google::Ads::AdWords::v201402::ImageAd', 'mutate/operations/operand/ad[ProductAd]/Ad.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/Media.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'getResponse/rval/entries/ad[ImageAd]/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutate/operations/operand/ad[RichMediaAd]/url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia/urls/value' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TextAd]/devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/value/ad[TemplateAd]/adUnionId/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'Fault/detail/ApiExceptionFault/errors[RejectedError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/exemptionRequests/key' => 'Google::Ads::AdWords::v201402::PolicyViolationKey', 'mutateResponse/rval/partialFailureErrors[StatsQueryError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'Fault/detail/ApiExceptionFault/errors[ExperimentError]' => 'Google::Ads::AdWords::v201402::ExperimentError', 'Fault/detail/ApiExceptionFault/errors[QuotaCheckError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[AuthenticationError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[MobileImageAd]/image/dimensions/value' => 'Google::Ads::AdWords::v201402::Dimensions', 'Fault/detail/ApiExceptionFault/errors[RangeError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia/urls/value' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/urls/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia' => 'Google::Ads::AdWords::v201402::Media', 'getResponse/rval/entries/ad[ThirdPartyRedirectAd]/isTagged' => 'SOAP::WSDL::XSD::Typelib::Builtin::boolean', 'queryResponse/rval/entries/ad[TemplateAd]/adAsImage/urls' => 'Google::Ads::AdWords::v201402::Media_Size_StringMapEntry', 'queryResponse/rval/entries/ad[TemplateAd]/adAsImage/dimensions/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'mutateResponse/rval/partialFailureErrors[SizeLimitError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[ClientTermsError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia/referenceId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/partialFailureErrors[RejectedError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'get/serviceSelector/paging/startIndex' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'getResponse/rval/entries/ad[MobileImageAd]/image/data' => 'SOAP::WSDL::XSD::Typelib::Builtin::base64Binary', 'mutateResponse/rval/partialFailureErrors[AuthenticationError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia/mimeType' => 'Google::Ads::AdWords::v201402::Media::MimeType', 'Fault/detail/ApiExceptionFault/errors[PolicyViolationError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[ReadOnlyError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/durationMillis' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutate/operations/operand/ad[TemplateAd]/url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia/dimensions/value' => 'Google::Ads::AdWords::v201402::Dimensions', 'queryResponse/rval/entries/ad[TemplateAd]/dimensions/width' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutateResponse/rval/partialFailureErrors[AdxError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[AdError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[MobileImageAd]/image/dimensions/value/width' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'getResponse/rval/entries/ad[MobileImageAd]/image/sourceUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[MobileImageAd]/Ad.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[ImageAd]/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[PagingError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/adAsImage' => 'Google::Ads::AdWords::v201402::Image', 'mutateResponse/rval/partialFailureErrors[ImageError]/reason' => 'Google::Ads::AdWords::v201402::ImageError::Reason', 'Fault/detail/ApiExceptionFault/errors[EntityNotFound]' => 'Google::Ads::AdWords::v201402::EntityNotFound', 'getResponse/rval/entries/forwardCompatibilityMap' => 'Google::Ads::AdWords::v201402::String_StringMapEntry', 'getResponse/rval/entries/ad[MobileImageAd]/image/referenceId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'Fault/detail/ApiExceptionFault/errors[ImageError]/reason' => 'Google::Ads::AdWords::v201402::ImageError::Reason', 'mutate/operations/operand/ad[MobileAd]/devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'queryResponse/rval/entries/ad[ImageAd]/image/fileSize' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'getResponse/rval/entries/ad[TemplateAd]/dimensions/height' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'getResponse/rval/entries/ad[DeprecatedAd]/type' => 'Google::Ads::AdWords::v201402::DeprecatedAd::Type', 'mutateResponse/rval/partialFailureErrors[AdGroupAdCountLimitExceeded]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[MobileImageAd]/image/dimensions/value/width' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutateResponse/rval/partialFailureErrors[InternalApiError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/urls/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]' => 'Google::Ads::AdWords::v201402::Video', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia/dimensions/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/referenceId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/dimensions/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'Fault/detail/ApiExceptionFault/errors[StringLengthError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[PolicyViolationError]/key/violatingText' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[RequestError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[QuotaCheckError]' => 'Google::Ads::AdWords::v201402::QuotaCheckError', 'Fault/detail/ApiExceptionFault/errors[ExperimentError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[AuthenticationError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/adAsImage/urls/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/readyToPlayOnTheWeb' => 'SOAP::WSDL::XSD::Typelib::Builtin::boolean', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/referenceId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutate/operations/operand/ad[ImageAd]/image/type' => 'Google::Ads::AdWords::v201402::Media::MediaType', 'queryResponse/rval/entries/ad[ImageAd]/image/urls/value' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[EntityCountLimitExceeded]/existingCount' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'queryResponse/rval/entries/ad[RichMediaAd]/impressionBeaconUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia' => 'Google::Ads::AdWords::v201402::Media', 'mutateResponse/rval/value/ad[RichMediaAd]/url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[ProductAd]' => 'Google::Ads::AdWords::v201402::ProductAd', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia/urls' => 'Google::Ads::AdWords::v201402::Media_Size_StringMapEntry', 'getResponse/rval/entries/ad[DynamicSearchAd]/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/value/ad[DynamicSearchAd]/url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TextAd]/headline' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[ImageError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[MobileImageAd]/image/mediaId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'getResponse/rval/entries/ad[DynamicSearchAd]/url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia/urls/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/dimensions/value' => 'Google::Ads::AdWords::v201402::Dimensions', 'mutate/operations/operand/adGroupId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'getResponse/rval/entries/ad[DynamicSearchAd]/displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[MobileAd]/businessName' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[RateExceededError]/rateName' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[RichMediaAd]/adDuration' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutateResponse/rval/partialFailureErrors[QueryError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/adAsImage/data' => 'SOAP::WSDL::XSD::Typelib::Builtin::base64Binary', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/urls/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/dimensions/value' => 'Google::Ads::AdWords::v201402::Dimensions', 'Fault/detail/ApiExceptionFault/errors[ImageError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[ImageAd]/image/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[MobileImageAd]/devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/sourceUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[StatsQueryError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/Ad.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[DeprecatedAd]' => 'Google::Ads::AdWords::v201402::DeprecatedAd', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/mediaId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'queryResponse/rval/entries/adGroupId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/fileSize' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'queryResponse/rval/entries/ad[ImageAd]/image' => 'Google::Ads::AdWords::v201402::Image', 'mutateResponse/rval/partialFailureErrors[AdError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[DistinctError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[ImageAd]/image/urls/value' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/duration' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutate/operations/operand/ad[MobileAd]/phoneNumber' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/urls' => 'Google::Ads::AdWords::v201402::Media_Size_StringMapEntry', 'queryResponse/rval/entries/ad[TemplateAd]/url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/adAsImage/dimensions/value/height' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'Fault/detail/ApiExceptionFault/errors[AdGroupAdError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia/dimensions/value' => 'Google::Ads::AdWords::v201402::Dimensions', 'getResponse/rval/entries/ad[ImageAd]/devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/partialFailureErrors[QuotaCheckError]/reason' => 'Google::Ads::AdWords::v201402::QuotaCheckError::Reason', 'getResponse/rval/entries/ad[MobileAd]/url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[ImageAd]/url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[DeprecatedAd]/url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutateResponse/rval/value/ad[ImageAd]/image/dimensions/value/height' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutateResponse/rval/value/ad[MobileAd]/phoneNumber' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[DeprecatedAd]/Ad.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia/dimensions/value/width' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'queryResponse/rval/entries/ad[MobileAd]/headline' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/dimensions/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'mutateResponse/rval/partialFailureErrors[DateError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[MobileAd]/mobileCarriers' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[ThirdPartyRedirectAd]/dimensions/width' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]' => 'Google::Ads::AdWords::v201402::Audio', 'Fault/detail/ApiExceptionFault/errors[PolicyViolationError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[InternalApiError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[DatabaseError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[ThirdPartyRedirectAd]/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'getResponse/rval/entries/ad[ImageAd]/image/dimensions/value/width' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutateResponse/rval/value/ad[ImageAd]/image/dimensions' => 'Google::Ads::AdWords::v201402::Media_Size_DimensionsMapEntry', 'mutate/operations/operand/ad[TemplateAd]/adAsImage/dimensions/value' => 'Google::Ads::AdWords::v201402::Dimensions', 'queryResponse/rval/entries/ad[MobileImageAd]/image/creationTime' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'get/serviceSelector/ordering' => 'Google::Ads::AdWords::v201402::OrderBy', 'mutateResponse/rval/value/ad[TextAd]/description2' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[PolicyViolationError]/isExemptable' => 'SOAP::WSDL::XSD::Typelib::Builtin::boolean', 'Fault/detail/ApiExceptionFault/errors[MediaError]/reason' => 'Google::Ads::AdWords::v201402::MediaError::Reason', 'mutateResponse/rval/partialFailureErrors[DateError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[ImageAd]/image/dimensions/value/width' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutateResponse/rval/value/ad[ImageAd]/image/urls/value' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/adAsImage/type' => 'Google::Ads::AdWords::v201402::Media::MediaType', 'queryResponse/rval/entries/ad[ThirdPartyRedirectAd]/impressionBeaconUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[AdGroupAdError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[SizeLimitError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia/referenceId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'getResponse/rval/entries/ad[MobileAd]/displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/dimensions/value/height' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutate/operations/operand/ad[MobileImageAd]/image/fileSize' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia/creationTime' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[RequiredError]/reason' => 'Google::Ads::AdWords::v201402::RequiredError::Reason', 'Fault/detail/ApiExceptionFault/errors[SelectorError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[NotEmptyError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/streamingUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[ThirdPartyRedirectAd]/dimensions' => 'Google::Ads::AdWords::v201402::Dimensions', 'Fault/detail/ApiExceptionFault/errors[IdError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[AdxError]/reason' => 'Google::Ads::AdWords::v201402::AdxError::Reason', 'mutateResponse/rval/value/ad[RichMediaAd]/impressionBeaconUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[InternalApiError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[DatabaseError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[DistinctError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[ReadOnlyError]/reason' => 'Google::Ads::AdWords::v201402::ReadOnlyError::Reason', 'getResponse/rval/entries/ad[RichMediaAd]/url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[NullError]/reason' => 'Google::Ads::AdWords::v201402::NullError::Reason', 'mutateResponse/rval/value/ad[TemplateAd]/adAsImage/dimensions/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'mutateResponse/rval/partialFailureErrors[AdxError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/urls' => 'Google::Ads::AdWords::v201402::Media_Size_StringMapEntry', 'Fault/detail/ApiExceptionFault/errors[IdError]/reason' => 'Google::Ads::AdWords::v201402::IdError::Reason', 'mutateResponse/rval/value/ad[ImageAd]/image/mediaId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'queryResponse/rval/entries/ad[TemplateAd]/dimensions' => 'Google::Ads::AdWords::v201402::Dimensions', 'queryResponse/rval/entries/ad[MobileImageAd]/image/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/dimensions' => 'Google::Ads::AdWords::v201402::Media_Size_DimensionsMapEntry', 'mutateResponse/rval/partialFailureErrors[EntityCountLimitExceeded]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[PagingError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/durationMillis' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/mimeType' => 'Google::Ads::AdWords::v201402::Media::MimeType', 'mutateResponse/rval/value/ad[DeprecatedAd]/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia/type' => 'Google::Ads::AdWords::v201402::Media::MediaType', 'mutateResponse/rval/partialFailureErrors[StringLengthError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[RichMediaAd]/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[MobileImageAd]/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'Fault/detail/ApiExceptionFault/errors[ExperimentError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[DynamicSearchAd]/Ad.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[RichMediaAd]/snippet' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[ForwardCompatibilityError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[ImageAd]/image/dimensions/value/height' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutateResponse/rval/partialFailureErrors[EntityCountLimitExceeded]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[MobileImageAd]/image/urls/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/Media.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[MobileAd]/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutate/operations/operand/forwardCompatibilityMap' => 'Google::Ads::AdWords::v201402::String_StringMapEntry', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/urls/value' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors' => 'Google::Ads::AdWords::v201402::ApiError', 'Fault/detail/ApiExceptionFault/errors[RequestError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[ThirdPartyRedirectAd]/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[RichMediaAd]' => 'Google::Ads::AdWords::v201402::RichMediaAd', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/mediaId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/type' => 'Google::Ads::AdWords::v201402::TemplateElementField::Type', 'queryResponse/rval/entries/ad[TextAd]/headline' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/dimensions' => 'Google::Ads::AdWords::v201402::Media_Size_DimensionsMapEntry', 'getResponse/rval/entries/ad[MobileImageAd]/Ad.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[RateExceededError]/reason' => 'Google::Ads::AdWords::v201402::RateExceededError::Reason', 'queryResponse/rval/entries/ad[ThirdPartyRedirectAd]/displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[InternalApiError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[AdGroupAdCountLimitExceeded]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/dimensions/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/Media.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault' => 'Google::Ads::AdWords::v201402::ApiException', 'queryResponse/rval/entries/ad[RichMediaAd]/dimensions/width' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutateResponse/rval/partialFailureErrors[MediaError]/trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/urls' => 'Google::Ads::AdWords::v201402::Media_Size_StringMapEntry', 'mutate/operations/operand/ad[ImageAd]/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'Fault/detail/ApiExceptionFault/errors[QuotaCheckError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[AuthorizationError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/adUnionId[TempAdUnionId]/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'queryResponse/rval/entries/ad[TemplateAd]/adUnionId/AdUnionId.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/dimensions/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/creationTime' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[MobileImageAd]/image/urls/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'getResponse/rval/entries/ad[RichMediaAd]/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[ThirdPartyRedirectAd]/adAttributes' => 'Google::Ads::AdWords::v201402::RichMediaAd::AdAttribute', 'mutateResponse/rval/ListReturnValue.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/streamingUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/forwardCompatibilityMap/key' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TextAd]/description2' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/dimensions/value' => 'Google::Ads::AdWords::v201402::Dimensions', 'queryResponse/rval/entries/ad/url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[ImageAd]/image/referenceId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'Fault/detail/ApiExceptionFault/errors[NotEmptyError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[RequestError]/reason' => 'Google::Ads::AdWords::v201402::RequestError::Reason', 'mutateResponse/rval/partialFailureErrors[InternalApiError]' => 'Google::Ads::AdWords::v201402::InternalApiError', 'Fault/detail/ApiExceptionFault/errors[RequiredError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/dimensions/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'mutateResponse/rval/value/ad[ThirdPartyRedirectAd]/devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/fileSize' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'Fault/detail/ApiExceptionFault/errors[RangeError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'queryResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/youTubeVideoIdString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[PolicyViolationError]/externalPolicyDescription' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[AdError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[PolicyViolationError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[MobileImageAd]/image/type' => 'Google::Ads::AdWords::v201402::Media::MediaType', 'getResponse/rval/entries/ad/url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/streamingUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/approvalStatus' => 'Google::Ads::AdWords::v201402::AdGroupAd::ApprovalStatus', 'mutateResponse/rval/value/ad[MobileImageAd]/image/type' => 'Google::Ads::AdWords::v201402::Media::MediaType', 'query/query' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[AdGroupAdCountLimitExceeded]/reason' => 'Google::Ads::AdWords::v201402::EntityCountLimitExceeded::Reason', 'getResponse/rval/totalNumEntries' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia/dimensions/key' => 'Google::Ads::AdWords::v201402::Media::Size', 'mutateResponse/rval/value/ad' => 'Google::Ads::AdWords::v201402::Ad', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Audio]/urls' => 'Google::Ads::AdWords::v201402::Media_Size_StringMapEntry', 'queryResponse/rval/entries/ad[TemplateAd]/adAsImage/type' => 'Google::Ads::AdWords::v201402::Media::MediaType', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/creationTime' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[AdGroupAdError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value' => 'Google::Ads::AdWords::v201402::AdGroupAd', 'mutateResponse/rval/value/ad[ProductAd]/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia' => 'Google::Ads::AdWords::v201402::Media', 'mutateResponse/rval/value/ad[MobileImageAd]/image/name' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'Fault/detail/ApiExceptionFault/errors[RejectedError]' => 'Google::Ads::AdWords::v201402::RejectedError', 'getResponse/rval/entries/ad[MobileAd]/markupLanguages' => 'Google::Ads::AdWords::v201402::MarkupLanguageType', 'getResponse/rval/entries/ad[ThirdPartyRedirectAd]/isCookieTargeted' => 'SOAP::WSDL::XSD::Typelib::Builtin::boolean', 'getResponse/rval/entries/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/urls' => 'Google::Ads::AdWords::v201402::Media_Size_StringMapEntry', 'mutateResponse/rval/partialFailureErrors[NewEntityCreationError]/fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[ClientTermsError]/reason' => 'Google::Ads::AdWords::v201402::ClientTermsError::Reason', 'mutate/operations/operand/ad[RichMediaAd]/devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'mutate/operations/operand/ad[TemplateAd]/templateElements/fields/fieldMedia[Video]/dimensions' => 'Google::Ads::AdWords::v201402::Media_Size_DimensionsMapEntry', 'Fault/detail/ApiExceptionFault/errors[ExperimentError]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad/id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'getResponse/rval/entries/ad[MobileImageAd]/image/dimensions/value' => 'Google::Ads::AdWords::v201402::Dimensions', 'queryResponse/rval/entries/ad[ThirdPartyRedirectAd]' => 'Google::Ads::AdWords::v201402::RichMediaAd', 'mutate/operations/operand' => 'Google::Ads::AdWords::v201402::AdGroupAd', 'mutateResponse/rval/partialFailureErrors[AdGroupAdCountLimitExceeded]/ApiError.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutate/operations/operand/ad[TemplateAd]/adAsImage/Media.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/partialFailureErrors[AdxError]/errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'mutateResponse/rval/value/ad[TemplateAd]/adUnionId' => 'Google::Ads::AdWords::v201402::AdUnionId', 'getResponse/rval/entries/ad[ThirdPartyRedirectAd]/dimensions/height' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutateResponse/rval/value/ad[ImageAd]/image/dimensions/value/width' => 'SOAP::WSDL::XSD::Typelib::Builtin::int', 'mutateResponse/rval/value/ad[TemplateAd]/templateElements/fields/fieldMedia[Image]/mediaId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'getResponse/rval/entries/ad[DeprecatedAd]/displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'getResponse/rval/entries/ad[MobileImageAd]' => 'Google::Ads::AdWords::v201402::MobileImageAd', 'mutate/operations' => 'Google::Ads::AdWords::v201402::AdGroupAdOperation', 'mutateResponse/rval/value/ad[TemplateAd]/Ad.Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string' }; ; sub get_class { my $name = join '/', @{ $_[1] }; return $typemap_1->{ $name }; } sub get_typemap { return $typemap_1; } 1; __END__ __END__ =pod =head1 NAME Google::Ads::AdWords::v201402::TypeMaps::AdGroupAdService - typemap for AdGroupAdService =head1 DESCRIPTION Typemap created by SOAP::WSDL for map-based SOAP message parsers. =cut
gitpan/GOOGLE-ADWORDS-PERL-CLIENT
lib/Google/Ads/AdWords/v201402/TypeMaps/AdGroupAdService.pm
Perl
apache-2.0
218,763
package Google::Ads::AdWords::v201809::ConstantOperand::ConstantType; use strict; use warnings; sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201809'}; # derivation by restriction use base qw( SOAP::WSDL::XSD::Typelib::Builtin::string); 1; __END__ =pod =head1 NAME =head1 DESCRIPTION Perl data type class for the XML Schema defined simpleType ConstantOperand.ConstantType from the namespace https://adwords.google.com/api/adwords/cm/v201809. The types of constant operands. This clase is derived from SOAP::WSDL::XSD::Typelib::Builtin::string . SOAP::WSDL's schema implementation does not validate data, so you can use it exactly like it's base type. # Description of restrictions not implemented yet. =head1 METHODS =head2 new Constructor. =head2 get_value / set_value Getter and setter for the simpleType's value. =head1 OVERLOADING Depending on the simple type's base type, the following operations are overloaded Stringification Numerification Boolification Check L<SOAP::WSDL::XSD::Typelib::Builtin> for more information. =head1 AUTHOR Generated by SOAP::WSDL =cut
googleads/googleads-perl-lib
lib/Google/Ads/AdWords/v201809/ConstantOperand/ConstantType.pm
Perl
apache-2.0
1,127
package Paws::MarketplaceCommerceAnalytics; use Moose; sub service { 'marketplacecommerceanalytics' } sub version { '2015-07-01' } sub target_prefix { 'MarketplaceCommerceAnalytics20150701' } sub json_version { "1.1" } has max_attempts => (is => 'ro', isa => 'Int', default => 5); has retry => (is => 'ro', isa => 'HashRef', default => sub { { base => 'rand', type => 'exponential', growth_factor => 2 } }); has retriables => (is => 'ro', isa => 'ArrayRef', default => sub { [ ] }); with 'Paws::API::Caller', 'Paws::API::EndpointResolver', 'Paws::Net::V4Signature', 'Paws::Net::JsonCaller', 'Paws::Net::JsonResponse'; sub GenerateDataSet { my $self = shift; my $call_object = $self->new_with_coercions('Paws::MarketplaceCommerceAnalytics::GenerateDataSet', @_); return $self->caller->do_call($self, $call_object); } sub StartSupportDataExport { my $self = shift; my $call_object = $self->new_with_coercions('Paws::MarketplaceCommerceAnalytics::StartSupportDataExport', @_); return $self->caller->do_call($self, $call_object); } sub operations { qw/GenerateDataSet StartSupportDataExport / } 1; ### main pod documentation begin ### =head1 NAME Paws::MarketplaceCommerceAnalytics - Perl Interface to AWS AWS Marketplace Commerce Analytics =head1 SYNOPSIS use Paws; my $obj = Paws->service('MarketplaceCommerceAnalytics'); my $res = $obj->Method( Arg1 => $val1, Arg2 => [ 'V1', 'V2' ], # if Arg3 is an object, the HashRef will be used as arguments to the constructor # of the arguments type Arg3 => { Att1 => 'Val1' }, # if Arg4 is an array of objects, the HashRefs will be passed as arguments to # the constructor of the arguments type Arg4 => [ { Att1 => 'Val1' }, { Att1 => 'Val2' } ], ); =head1 DESCRIPTION Provides AWS Marketplace business intelligence data on-demand. =head1 METHODS =head2 GenerateDataSet(DataSetPublicationDate => Str, DataSetType => Str, DestinationS3BucketName => Str, RoleNameArn => Str, SnsTopicArn => Str, [CustomerDefinedValues => L<Paws::MarketplaceCommerceAnalytics::CustomerDefinedValues>, DestinationS3Prefix => Str]) Each argument is described in detail in: L<Paws::MarketplaceCommerceAnalytics::GenerateDataSet> Returns: a L<Paws::MarketplaceCommerceAnalytics::GenerateDataSetResult> instance Given a data set type and data set publication date, asynchronously publishes the requested data set to the specified S3 bucket and notifies the specified SNS topic once the data is available. Returns a unique request identifier that can be used to correlate requests with notifications from the SNS topic. Data sets will be published in comma-separated values (CSV) format with the file name {data_set_type}_YYYY-MM-DD.csv. If a file with the same name already exists (e.g. if the same data set is requested twice), the original file will be overwritten by the new file. Requires a Role with an attached permissions policy providing Allow permissions for the following actions: s3:PutObject, s3:GetBucketLocation, sns:GetTopicAttributes, sns:Publish, iam:GetRolePolicy. =head2 StartSupportDataExport(DataSetType => Str, DestinationS3BucketName => Str, FromDate => Str, RoleNameArn => Str, SnsTopicArn => Str, [CustomerDefinedValues => L<Paws::MarketplaceCommerceAnalytics::CustomerDefinedValues>, DestinationS3Prefix => Str]) Each argument is described in detail in: L<Paws::MarketplaceCommerceAnalytics::StartSupportDataExport> Returns: a L<Paws::MarketplaceCommerceAnalytics::StartSupportDataExportResult> instance Given a data set type and a from date, asynchronously publishes the requested customer support data to the specified S3 bucket and notifies the specified SNS topic once the data is available. Returns a unique request identifier that can be used to correlate requests with notifications from the SNS topic. Data sets will be published in comma-separated values (CSV) format with the file name {data_set_type}_YYYY-MM-DD'T'HH-mm-ss'Z'.csv. If a file with the same name already exists (e.g. if the same data set is requested twice), the original file will be overwritten by the new file. Requires a Role with an attached permissions policy providing Allow permissions for the following actions: s3:PutObject, s3:GetBucketLocation, sns:GetTopicAttributes, sns:Publish, iam:GetRolePolicy. =head1 PAGINATORS Paginator methods are helpers that repetively call methods that return partial results =head1 SEE ALSO This service class forms part of L<Paws> =head1 BUGS and CONTRIBUTIONS The source code is located here: https://github.com/pplu/aws-sdk-perl Please report bugs to: https://github.com/pplu/aws-sdk-perl/issues =cut
ioanrogers/aws-sdk-perl
auto-lib/Paws/MarketplaceCommerceAnalytics.pm
Perl
apache-2.0
4,711
package Paws::CloudDirectory::UpdateFacet; use Moose; has AttributeUpdates => (is => 'ro', isa => 'ArrayRef[Paws::CloudDirectory::FacetAttributeUpdate]'); has Name => (is => 'ro', isa => 'Str', required => 1); has ObjectType => (is => 'ro', isa => 'Str'); has SchemaArn => (is => 'ro', isa => 'Str', traits => ['ParamInHeader'], header_name => 'x-amz-data-partition', required => 1); use MooseX::ClassAttribute; class_has _api_call => (isa => 'Str', is => 'ro', default => 'UpdateFacet'); class_has _api_uri => (isa => 'Str', is => 'ro', default => '/amazonclouddirectory/2017-01-11/facet'); class_has _api_method => (isa => 'Str', is => 'ro', default => 'PUT'); class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::CloudDirectory::UpdateFacetResponse'); class_has _result_key => (isa => 'Str', is => 'ro'); 1; ### main pod documentation begin ### =head1 NAME Paws::CloudDirectory::UpdateFacet - Arguments for method UpdateFacet on Paws::CloudDirectory =head1 DESCRIPTION This class represents the parameters used for calling the method UpdateFacet on the Amazon CloudDirectory service. Use the attributes of this class as arguments to method UpdateFacet. You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to UpdateFacet. As an example: $service_obj->UpdateFacet(Att1 => $value1, Att2 => $value2, ...); Values for attributes that are native types (Int, String, Float, etc) can passed as-is (scalar values). Values for complex Types (objects) can be passed as a HashRef. The keys and values of the hashref will be used to instance the underlying object. =head1 ATTRIBUTES =head2 AttributeUpdates => ArrayRef[L<Paws::CloudDirectory::FacetAttributeUpdate>] List of attributes that need to be updated in a given schema Facet. Each attribute is followed by C<AttributeAction>, which specifies the type of update operation to perform. =head2 B<REQUIRED> Name => Str The name of the facet. =head2 ObjectType => Str The object type that is associated with the facet. See CreateFacetRequest$ObjectType for more details. Valid values are: C<"NODE">, C<"LEAF_NODE">, C<"POLICY">, C<"INDEX"> =head2 B<REQUIRED> SchemaArn => Str The Amazon Resource Name (ARN) that is associated with the Facet. For more information, see arns. =head1 SEE ALSO This class forms part of L<Paws>, documenting arguments for method UpdateFacet in L<Paws::CloudDirectory> =head1 BUGS and CONTRIBUTIONS The source code is located here: https://github.com/pplu/aws-sdk-perl Please report bugs to: https://github.com/pplu/aws-sdk-perl/issues =cut
ioanrogers/aws-sdk-perl
auto-lib/Paws/CloudDirectory/UpdateFacet.pm
Perl
apache-2.0
2,642
package VMOMI::ArrayOfHostVsanInternalSystemDeleteVsanObjectsResult; use parent 'VMOMI::ComplexType'; use strict; use warnings; our @class_ancestors = ( ); our @class_members = ( ['HostVsanInternalSystemDeleteVsanObjectsResult', 'HostVsanInternalSystemDeleteVsanObjectsResult', 1, 1], ); sub get_class_ancestors { return @class_ancestors; } sub get_class_members { my $class = shift; my @super_members = $class->SUPER::get_class_members(); return (@super_members, @class_members); } 1;
stumpr/p5-vmomi
lib/VMOMI/ArrayOfHostVsanInternalSystemDeleteVsanObjectsResult.pm
Perl
apache-2.0
513
#!/usr/bin/perl =pod Copyright (c) 2012, Salesforce.com, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of salesforce.com, inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. =cut package Perl::Koans::Scope; use warnings; use lib './lib'; use Perl::Koans; our $TEST = 1; ################ # your code goes below this line sub about_scope { # about_scope() my $foo = 100; my $bar = 200; is ($foo, __, 'use the most closely scoped variable -- part 1'); { my $foo = 10; is ($foo, __, 'use the most closely scoped variable -- part 2'); is ($bar, __, 'use the most closely scoped variable -- part 3'); } is ($foo, __, 'use the most closely scoped variable -- part 4'); for (my $foo = 0; $foo < 10; $foo++) { isnt($foo, __, 'use the most closely scoped variable -- part 5'); } is ($foo, __, 'use the most closely scoped variable -- part 6'); my $baz = 300; for ($baz = 0; $baz < 10; $baz++) { isnt ($baz, __, 'use the most closely scoped variable -- part 7'); } is ($baz, __, 'use the most closely scoped variable -- part 8'); return (Perl::Koans::get_return_code()); } sub about_local { # about_local() - allows you to modify variables for the current block is ($TEST, __, 'unmodified package variable -- part 1'); { local $TEST = 100; is ($TEST, __, 'locally modified package variable'); } is ($TEST, __, 'unmodified package variable -- part 2'); return (Perl::Koans::get_return_code()); } # your code goes above this line ################ unless (caller(0)) { run(@ARGV) or print_illumination(); exit(); } sub run { # run() -- runs all functions in this module my $results = 0; $results += about_scope(); $results += about_local(); ## record results somewhere in Perl::Koans namespace return ($results) ? bail($results) : $results; } 1;
forcedotcom/PerlKoans
about_scope.pl
Perl
bsd-3-clause
3,449
#!/usr/bin/perl # read from syscalls_darwin_unix.h while(<>){ if(/[0-9]+$/){ my $n = $&; $n += 0x2000000; printf '%s0x%x%s', $`, $n, $' }else{ print } }
8l/ucc-c-compiler
lib/syscalls_darwin.pl
Perl
mit
165
#!perl use strict; use warnings; use lib 'lib'; use Test::More; use Test::BDD::Cucumber::StepFile; use Business::OnlinePayment::BitPay::Client; use Try::Tiny; use Env; require Business::OnlinePayment::BitPay::KeyUtils; require 'features/step_definitions/helpers.pl'; my $pairingCode; my $client; my $token; our $error; my $pem; my $uri; $client = setClient(); Given 'the user pairs with BitPay with a valid pairing code', sub{ sleep 2; my $response = $client->get(path => "tokens"); my @data = $client->process_response($response); for my $mapp (values @data[0]){ for my $key (keys %$mapp) { $token = %$mapp{$key} if $key eq "merchant"; } } my $params = {token => $token, facade => "pos", id => $client->{id}}; $response = $client->post(path => "tokens", params => $params); @data = $client->process_response($response); $pairingCode = shift(shift(@data))->{'pairingCode'}; ok($pairingCode); }; Then 'the user is paired with BitPay', sub { my $params = {pairingCode => $pairingCode, id => $client->{id}}; my @data = $client->pair_pos_client($pairingCode); my $facade = shift(shift(@data))->{'facade'}; ok($facade eq "pos"); }; Given 'the user requests a client-side pairing', sub{ sleep 2; my @data = $client->pair_client(facade => 'pos'); $pairingCode = shift(shift(@data))->{'pairingCode'}; }; Then 'they will receive a claim code', sub{ ok($pairingCode =~ /\w{7}/); }; Given qr/the user fails to pair with "(.+)"/, sub { try { $client->pair_pos_client($1); } catch { $error = $_; } }; Then qr/they will receive an error matching "(.+)"/, sub { ok($error =~ /$1/i); }
bitpay/bitpay-perl
features/step_definitions/pairing_steps.pl
Perl
mit
1,713
use APR::Request; sub new { my ($class, $pool, %attrs) = @_; my $name = delete $attrs{name}; my $value = delete $attrs{value}; $name = delete $attrs{-name} unless defined $name; $value = delete $attrs{-value} unless defined $value; return unless defined $name and defined $value; my $cookie = $class->make($pool, $name, $class->freeze($value)); while(my ($k, $v) = each %attrs) { $k =~ s/^-//; $cookie->$k($v); } return $cookie; } sub freeze { return $_[1] } sub thaw { return shift->value }
oerdnj/rapache
libapreq2/glue/perl/xsbuilder/APR/Request/Cookie/Cookie.pm
Perl
apache-2.0
560
package Google::Ads::AdWords::v201409::CampaignCriterionService::ApiExceptionFault; use strict; use warnings; { # BLOCK to scope variables sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201409' } __PACKAGE__->__set_name('ApiExceptionFault'); __PACKAGE__->__set_nillable(); __PACKAGE__->__set_minOccurs(); __PACKAGE__->__set_maxOccurs(); __PACKAGE__->__set_ref(); use base qw( SOAP::WSDL::XSD::Typelib::Element Google::Ads::AdWords::v201409::ApiException ); } 1; =pod =head1 NAME Google::Ads::AdWords::v201409::CampaignCriterionService::ApiExceptionFault =head1 DESCRIPTION Perl data type class for the XML Schema defined element ApiExceptionFault from the namespace https://adwords.google.com/api/adwords/cm/v201409. A fault element of type ApiException. =head1 METHODS =head2 new my $element = Google::Ads::AdWords::v201409::CampaignCriterionService::ApiExceptionFault->new($data); Constructor. The following data structure may be passed to new(): $a_reference_to, # see Google::Ads::AdWords::v201409::ApiException =head1 AUTHOR Generated by SOAP::WSDL =cut
gitpan/GOOGLE-ADWORDS-PERL-CLIENT
lib/Google/Ads/AdWords/v201409/CampaignCriterionService/ApiExceptionFault.pm
Perl
apache-2.0
1,109
package Paws::CloudDirectory::GetSchemaAsJsonResponse; use Moose; has Document => (is => 'ro', isa => 'Str'); has Name => (is => 'ro', isa => 'Str'); has _request_id => (is => 'ro', isa => 'Str'); 1; ### main pod documentation begin ### =head1 NAME Paws::CloudDirectory::GetSchemaAsJsonResponse =head1 ATTRIBUTES =head2 Document => Str The JSON representation of the schema document. =head2 Name => Str The name of the retrieved schema. =head2 _request_id => Str =cut
ioanrogers/aws-sdk-perl
auto-lib/Paws/CloudDirectory/GetSchemaAsJsonResponse.pm
Perl
apache-2.0
493
#------------------------------------------------------------------------------ # File: WriteIPTC.pl # # Description: Write IPTC meta information # # Revisions: 12/15/2004 - P. Harvey Created #------------------------------------------------------------------------------ package Image::ExifTool::IPTC; use strict; # mandatory IPTC tags for each record my %mandatory = ( 1 => { 0 => 4, # EnvelopeRecordVersion }, 2 => { 0 => 4, # ApplicationRecordVersion }, 3 => { 0 => 4, # NewsPhotoVersion }, ); # manufacturer strings for IPTCPictureNumber my %manufacturer = ( 1 => 'Associated Press, USA', 2 => 'Eastman Kodak Co, USA', 3 => 'Hasselblad Electronic Imaging, Sweden', 4 => 'Tecnavia SA, Switzerland', 5 => 'Nikon Corporation, Japan', 6 => 'Coatsworth Communications Inc, Canada', 7 => 'Agence France Presse, France', 8 => 'T/One Inc, USA', 9 => 'Associated Newspapers, UK', 10 => 'Reuters London', 11 => 'Sandia Imaging Systems Inc, USA', 12 => 'Visualize, Spain', ); my %iptcCharsetInv = ( 'UTF8' => "\x1b%G", 'UTF-8' => "\x1b%G" ); # ISO 2022 Character Coding Notes # ------------------------------- # Character set designation: (0x1b I F, or 0x1b I I F) # Initial character 0x1b (ESC) # Intermediate character I: # 0x28 ('(') - G0, 94 chars # 0x29 (')') - G1, 94 chars # 0x2a ('*') - G2, 94 chars # 0x2b ('+') - G3, 94 chars # 0x2c (',') - G1, 96 chars # 0x2d ('-') - G2, 96 chars # 0x2e ('.') - G3, 96 chars # 0x24 I ('$I') - multiple byte graphic sets (I from above) # I 0x20 ('I ') - dynamically redefinable character sets # Final character: # 0x30 - 0x3f = private character set # 0x40 - 0x7f = standardized character set # Character set invocation: # G0 : SI = 0x15 # G1 : SO = 0x14, LS1R = 0x1b 0x7e ('~') # G2 : LS2 = 0x1b 0x6e ('n'), LS2R = 0x1b 0x7d ('}') # G3 : LS3 = 0x1b 0x6f ('o'), LS3R = 0x1b 0x7c ('|') # (the locking shift "R" codes shift into 0x80-0xff space) # Single character invocation: # G2 : SS2 = 0x1b 0x8e (or 0x4e in 7-bit) # G3 : SS3 = 0x1b 0x8f (or 0x4f in 7-bit) # Control chars (designated and invoked) # C0 : 0x1b 0x21 F (0x21 = '!') # C1 : 0x1b 0x22 F (0x22 = '"') # Complete codes (control+graphics, designated and invoked) # 0x1b 0x25 F (0x25 = '%') # 0x1b 0x25 I F # 0x1b 0x25 0x47 ("\x1b%G") - UTF-8 # 0x1b 0x25 0x40 ("\x1b%@") - return to ISO 2022 # ------------------------------- #------------------------------------------------------------------------------ # Inverse print conversion for CodedCharacterSet # Inputs: 0) value sub PrintInvCodedCharset($) { my $val = shift; my $code = $iptcCharsetInv{uc($val)}; unless ($code) { if (($code = $val) =~ s/ESC /\x1b/g) { # translate ESC chars $code =~ s/, \x1b/\x1b/g; # remove comma separators $code =~ tr/ //d; # remove spaces } else { warn "Bad syntax (use 'UTF8' or 'ESC X Y[, ...]')\n"; } } return $code; } #------------------------------------------------------------------------------ # validate raw values for writing # Inputs: 0) ExifTool object reference, 1) tagInfo hash reference, # 2) raw value reference # Returns: error string or undef (and possibly changes value) on success sub CheckIPTC($$$) { my ($exifTool, $tagInfo, $valPtr) = @_; my $format = $$tagInfo{Format} || $tagInfo->{Table}->{FORMAT} || ''; if ($format =~ /^int(\d+)/) { my $bytes = int(($1 || 0) / 8); if ($bytes ne 1 and $bytes ne 2 and $bytes ne 4) { return "Can't write $bytes-byte integer"; } my $val = $$valPtr; unless (Image::ExifTool::IsInt($val)) { return 'Not an integer' unless Image::ExifTool::IsHex($val); $val = $$valPtr = hex($val); } my $n; for ($n=0; $n<$bytes; ++$n) { $val >>= 8; } return "Value too large for $bytes-byte format" if $val; } elsif ($format =~ /^(string|digits)\[?(\d+),?(\d*)\]?$/) { my ($fmt, $minlen, $maxlen) = ($1, $2, $3); my $len = length $$valPtr; if ($fmt eq 'digits') { return 'Non-numeric characters in value' unless $$valPtr =~ /^\d+$/; # left pad with zeros if necessary $$valPtr = ('0' x ($len - $minlen)) . $$valPtr if $len < $minlen; } if ($minlen) { $maxlen or $maxlen = $minlen; return "String too short (minlen is $minlen)" if $len < $minlen; return "String too long (maxlen is $maxlen)" if $len > $maxlen; } } else { return "Bad IPTC Format ($format)"; } return undef; } #------------------------------------------------------------------------------ # format IPTC data for writing # Inputs: 0) ExifTool object ref, 1) tagInfo pointer, # 2) value reference (changed if necessary), # 3) reference to character set for translation (changed if necessary) # 4) record number, 5) flag set to read value (instead of write) sub FormatIPTC($$$$$;$) { my ($exifTool, $tagInfo, $valPtr, $xlatPtr, $rec, $read) = @_; return unless $$tagInfo{Format}; if ($$tagInfo{Format} =~ /^int(\d+)/) { if ($read) { my $len = length($$valPtr); if ($len <= 8) { # limit integer conversion to 8 bytes long my $val = 0; my $i; for ($i=0; $i<$len; ++$i) { $val = $val * 256 + ord(substr($$valPtr, $i, 1)); } $$valPtr = $val; } } else { my $len = int(($1 || 0) / 8); if ($len == 1) { # 1 byte $$valPtr = chr($$valPtr); } elsif ($len == 2) { # 2-byte integer $$valPtr = pack('n', $$valPtr); } else { # 4-byte integer $$valPtr = pack('N', $$valPtr); } } } elsif ($$tagInfo{Format} =~ /^string/) { if ($rec == 1) { if ($$tagInfo{Name} eq 'CodedCharacterSet') { $$xlatPtr = HandleCodedCharset($exifTool, $$valPtr); } } elsif ($$xlatPtr and $rec < 7 and $$valPtr =~ /[\x80-\xff]/) { TranslateCodedString($exifTool, $valPtr, $xlatPtr, $read); } } } #------------------------------------------------------------------------------ # generate IPTC-format date # Inputs: 0) EXIF-format date string (YYYY:MM:DD) or date/time string # Returns: IPTC-format date string (YYYYMMDD), or undef and issue warning on error sub IptcDate($) { my $val = shift; unless ($val =~ s/.*(\d{4}):?(\d{2}):?(\d{2}).*/$1$2$3/) { warn "Invalid date format (use YYYY:MM:DD)\n"; undef $val; } return $val; } #------------------------------------------------------------------------------ # generate IPTC-format time # Inputs: 0) EXIF-format time string (HH:MM:SS[+/-HH:MM]) or date/time string # Returns: IPTC-format time string (HHMMSS+HHMM), or undef and issue warning on error sub IptcTime($) { my $val = shift; if ($val =~ /\s*\b(\d{1,2})(:?)(\d{2})(:?)(\d{2})(\S*)\s*$/ and ($2 or not $4)) { $val = sprintf("%.2d%.2d%.2d",$1,$3,$5); my $tz = $6; if ($tz =~ /([+-]\d{1,2}):?(\d{2})/) { $tz = sprintf("%+.2d%.2d",$1,$2); } elsif ($tz !~ /Z/i) { # use local system timezone by default (note: it is difficult to use # the proper local timezone for this date/time because the date tag # is written separately so we don't know what the local timezone offset # really should be for this date/time) my $now = time; my @tm = localtime($now); ($tz = Image::ExifTool::TimeZoneString(\@tm, $now)) =~ tr/://d; } else { $tz = '+0000'; # don't know the time zone } $val .= $tz; } else { warn "Invalid time format (use HH:MM:SS[+/-HH:MM])\n"; undef $val; # time format error } return $val; } #------------------------------------------------------------------------------ # Convert picture number # Inputs: 0) value # Returns: Converted value sub ConvertPictureNumber($) { my $val = shift; if ($val eq "\0" x 16) { $val = 'Unknown'; } elsif (length $val >= 16) { my @vals = unpack('nNA8n', $val); $val = $vals[0]; my $manu = $manufacturer{$val}; $val .= " ($manu)" if $manu; $val .= ', equip ' . $vals[1]; $vals[2] =~ s/(\d{4})(\d{2})(\d{2})/$1:$2:$3/; $val .= ", $vals[2], no. $vals[3]"; } else { $val = '<format error>' } return $val; } #------------------------------------------------------------------------------ # Inverse picture number conversion # Inputs: 0) value # Returns: Converted value (or undef on error) sub InvConvertPictureNumber($) { my $val = shift; $val =~ s/\(.*\)//g; # remove manufacturer description $val =~ tr/://d; # remove date separators $val =~ tr/0-9/ /c; # turn remaining non-numbers to spaces my @vals = split ' ', $val; if (@vals >= 4) { $val = pack('nNA8n', @vals); } elsif ($val =~ /unknown/i) { $val = "\0" x 16; } else { undef $val; } return $val; } #------------------------------------------------------------------------------ # Write IPTC data record # Inputs: 0) ExifTool object ref, 1) source dirInfo ref, 2) tag table ref # Returns: IPTC data block (may be empty if no IPTC data) # Notes: Increments ExifTool CHANGED flag for each tag changed sub DoWriteIPTC($$$) { my ($exifTool, $dirInfo, $tagTablePtr) = @_; my $verbose = $exifTool->Options('Verbose'); my $out = $exifTool->Options('TextOut'); # avoid editing IPTC directory unless necessary: # - improves speed # - avoids changing current MD5 digest unnecessarily # - avoids adding mandatory tags unless some other IPTC is changed unless (exists $exifTool->{EDIT_DIRS}->{$$dirInfo{DirName}}) { print $out "$$exifTool{INDENT} [nothing changed]\n" if $verbose; return undef; } my $dataPt = $$dirInfo{DataPt}; unless ($dataPt) { my $emptyData = ''; $dataPt = \$emptyData; } my $start = $$dirInfo{DirStart} || 0; my $dirLen = $$dirInfo{DirLen}; my ($tagInfo, %iptcInfo, $tag); # begin by assuming IPTC is coded in Latin unless otherwise specified my $xlat = $exifTool->Options('Charset'); undef $xlat if $xlat eq 'Latin'; # make sure our dataLen is defined (note: allow zero length directory) unless (defined $dirLen) { my $dataLen = $$dirInfo{DataLen}; $dataLen = length($$dataPt) unless defined $dataLen; $dirLen = $dataLen - $start; } # quick check for improperly byte-swapped IPTC if ($dirLen >= 4 and substr($$dataPt, $start, 1) ne "\x1c" and substr($$dataPt, $start + 3, 1) eq "\x1c") { $exifTool->Warn('IPTC data was improperly byte-swapped'); my $newData = pack('N*', unpack('V*', substr($$dataPt, $start, $dirLen) . "\0\0\0")); $dataPt = \$newData; $start = 0; # NOTE: MUST NOT access $dirInfo DataPt, DirStart or DataLen after this! } # generate lookup so we can find the record numbers my %recordNum; foreach $tag (Image::ExifTool::TagTableKeys($tagTablePtr)) { $tagInfo = $tagTablePtr->{$tag}; $$tagInfo{SubDirectory} or next; my $table = $tagInfo->{SubDirectory}->{TagTable} or next; my $subTablePtr = Image::ExifTool::GetTagTable($table); $recordNum{$subTablePtr} = $tag; } # loop through new values and accumulate all IPTC information # into lists based on their IPTC record type foreach $tagInfo ($exifTool->GetNewTagInfoList()) { my $table = $$tagInfo{Table}; my $record = $recordNum{$table}; # ignore tags we aren't writing to this directory next unless defined $record; $iptcInfo{$record} = [] unless defined $iptcInfo{$record}; push @{$iptcInfo{$record}}, $tagInfo; } # get sorted list of records used. Might as well be organized and # write our records in order of record number first, then tag number my @recordList = sort { $a <=> $b } keys %iptcInfo; my ($record, %set); foreach $record (@recordList) { # sort tagInfo lists by tagID @{$iptcInfo{$record}} = sort { $$a{TagID} <=> $$b{TagID} } @{$iptcInfo{$record}}; # build hash of all tagIDs to set foreach $tagInfo (@{$iptcInfo{$record}}) { $set{$record}->{$$tagInfo{TagID}} = $tagInfo; } } # run through the old IPTC data, inserting our records in # sequence and deleting existing records where necessary # (the IPTC specification states that records must occur in # numerical order, but tags within records need not be ordered) my $pos = $start; my $tail = $pos; # old data written up to this point my $dirEnd = $start + $dirLen; my $newData = ''; my $lastRec = -1; my $lastRecPos = 0; my $allMandatory = 0; my %foundRec; # found flags: 0x01-existed before, 0x02-deleted, 0x04-created for (;;$tail=$pos) { # get next IPTC record from input directory my ($id, $rec, $tag, $len, $valuePtr); if ($pos + 5 <= $dirEnd) { my $buff = substr($$dataPt, $pos, 5); ($id, $rec, $tag, $len) = unpack("CCCn", $buff); if ($id == 0x1c) { if ($rec < $lastRec) { if ($rec == 0) { return undef if $exifTool->Warn("IPTC record 0 encountered, subsequent records ignored", 1); undef $rec; $pos = $dirEnd; $len = 0; } else { return undef if $exifTool->Warn("IPTC doesn't conform to spec: Records out of sequence", 1); } } # handle extended IPTC entry if necessary $pos += 5; # step to after field header if ($len & 0x8000) { my $n = $len & 0x7fff; # get num bytes in length field if ($pos + $n <= $dirEnd and $n <= 8) { # determine length (a big-endian, variable sized int) for ($len = 0; $n; ++$pos, --$n) { $len = $len * 256 + ord(substr($$dataPt, $pos, 1)); } } else { $len = $dirEnd; # invalid length } } $valuePtr = $pos; $pos += $len; # step $pos to next entry # make sure we don't go past the end of data # (this can only happen if original data is bad) $pos = $dirEnd if $pos > $dirEnd; } else { undef $rec; } } if (not defined $rec or $rec != $lastRec) { # write out all our records that come before this one for (;;) { my $newRec = $recordList[0]; if (not defined $newRec or $newRec != $lastRec) { # handle mandatory tags in last record unless it was empty if (length $newData > $lastRecPos) { if ($allMandatory > 1) { # entire lastRec contained mandatory tags, and at least one tag # was deleted, so delete entire record unless we specifically # added a mandatory tag my $num = 0; foreach (keys %{$foundRec{$lastRec}}) { my $code = $foundRec{$lastRec}->{$_}; $num = 0, last if $code & 0x04; ++$num if ($code & 0x03) == 0x01; } if ($num) { $newData = substr($newData, 0, $lastRecPos); $verbose > 1 and print $out " - $num mandatory tags\n"; } } elsif ($mandatory{$lastRec} and $tagTablePtr eq \%Image::ExifTool::IPTC::Main) { # add required mandatory tags my $mandatory = $mandatory{$lastRec}; my ($mandTag, $subTablePtr); foreach $mandTag (sort { $a <=> $b } keys %$mandatory) { next if $foundRec{$lastRec}->{$mandTag}; unless ($subTablePtr) { $tagInfo = $tagTablePtr->{$lastRec}; $tagInfo and $$tagInfo{SubDirectory} or warn("WriteIPTC: Internal error 1\n"), next; $tagInfo->{SubDirectory}->{TagTable} or next; $subTablePtr = Image::ExifTool::GetTagTable($tagInfo->{SubDirectory}->{TagTable}); } $tagInfo = $subTablePtr->{$mandTag} or warn("WriteIPTC: Internal error 2\n"), next; my $value = $mandatory->{$mandTag}; $exifTool->VerboseValue("+ IPTC:$$tagInfo{Name}", $value, ' (mandatory)'); # apply necessary format conversions FormatIPTC($exifTool, $tagInfo, \$value, \$xlat, $lastRec); $len = length $value; # generate our new entry my $entry = pack("CCCn", 0x1c, $lastRec, $mandTag, length($value)); $newData .= $entry . $value; # add entry to new IPTC data ++$exifTool->{CHANGED}; } } } last unless defined $newRec; $lastRec = $newRec; $lastRecPos = length $newData; $allMandatory = 1; } $tagInfo = ${$iptcInfo{$newRec}}[0]; my $newTag = $$tagInfo{TagID}; # compare current entry with entry next in line to write out # (write out our tags in numerical order even though # this isn't required by the IPTC spec) last if defined $rec and $rec <= $newRec; my $nvHash = $exifTool->GetNewValueHash($tagInfo); # only add new values if... my ($doSet, @values); my $found = $foundRec{$newRec}->{$newTag} || 0; if ($found & 0x02) { # ...tag existed before and was deleted $doSet = 1; } elsif ($$tagInfo{List}) { # ...tag is List and it existed before or we are creating it $doSet = 1 if $found or Image::ExifTool::IsCreating($nvHash); } else { # ...tag didn't exist before and we are creating it $doSet = 1 if not $found and Image::ExifTool::IsCreating($nvHash); } if ($doSet) { @values = Image::ExifTool::GetNewValues($nvHash); @values and $foundRec{$newRec}->{$newTag} = $found | 0x04; # write tags for each value in list my $value; foreach $value (@values) { $exifTool->VerboseValue("+ IPTC:$$tagInfo{Name}", $value); # reset allMandatory flag if a non-mandatory tag is written if ($allMandatory) { my $mandatory = $mandatory{$newRec}; $allMandatory = 0 unless $mandatory and $mandatory->{$newTag}; } # apply necessary format conversions FormatIPTC($exifTool, $tagInfo, \$value, \$xlat, $newRec); # (note: IPTC string values are NOT null terminated) $len = length $value; # generate our new entry my $entry = pack("CCC", 0x1c, $newRec, $newTag); if ($len <= 0x7fff) { $entry .= pack("n", $len); } else { # extended dataset tag $entry .= pack("nN", 0x8004, $len); } $newData .= $entry . $value; # add entry to new IPTC data ++$exifTool->{CHANGED}; } } # remove this tagID from the sorted write list shift @{$iptcInfo{$newRec}}; shift @recordList unless @{$iptcInfo{$newRec}}; } # all done if no more records to write last unless defined $rec; # update last record variables $lastRec = $rec; $lastRecPos = length $newData; $allMandatory = 1; } # set flag indicating we found this tag $foundRec{$rec}->{$tag} = 1; # write out this record unless we are setting it with a new value $tagInfo = $set{$rec}->{$tag}; if ($tagInfo) { my $nvHash = $exifTool->GetNewValueHash($tagInfo); $len = $pos - $valuePtr; my $val = substr($$dataPt, $valuePtr, $len); my $oldXlat = $xlat; FormatIPTC($exifTool, $tagInfo, \$val, \$xlat, $rec, 1); if (Image::ExifTool::IsOverwriting($nvHash, $val)) { $xlat = $oldXlat; # don't change translation (not writing this value) $exifTool->VerboseValue("- IPTC:$$tagInfo{Name}", $val); ++$exifTool->{CHANGED}; # set deleted flag to indicate we found and deleted this tag $foundRec{$rec}->{$tag} |= 0x02; # set allMandatory flag to 2 indicating a tag was removed $allMandatory and ++$allMandatory; next; } } elsif ($rec == 1 and $tag == 90) { # handle CodedCharacterSet tag my $val = substr($$dataPt, $valuePtr, $pos - $valuePtr); $xlat = HandleCodedCharset($exifTool, $val); } # reset allMandatory flag if a non-mandatory tag is written if ($allMandatory) { my $mandatory = $mandatory{$rec}; unless ($mandatory and $mandatory->{$tag}) { $allMandatory = 0; } } # write out the record $newData .= substr($$dataPt, $tail, $pos-$tail); } # make sure the rest of the data is zero if ($tail < $dirEnd) { my $trailer = substr($$dataPt, $tail, $dirEnd-$tail); if ($trailer =~ /[^\0]/) { return undef if $exifTool->Warn('Unrecognized data in IPTC trailer', 1); } } return $newData; } #------------------------------------------------------------------------------ # Write IPTC data record and calculate NewIPTCDigest # Inputs: 0) ExifTool object ref, 1) source dirInfo ref, 2) tag table ref # Returns: IPTC data block (may be empty if no IPTC data) # Notes: Increments ExifTool CHANGED flag for each tag changed sub WriteIPTC($$$) { my ($exifTool, $dirInfo, $tagTablePtr) = @_; $exifTool or return 1; # allow dummy access to autoload this package my $newData = DoWriteIPTC($exifTool, $dirInfo, $tagTablePtr); return $newData unless eval 'require Digest::MD5'; my $dataPt; if (defined $newData) { $dataPt = \$newData; } else { $dataPt = $$dirInfo{DataPt}; if ($$dirInfo{DirStart} or length($$dataPt) != $$dirInfo{DirLen}) { my $buff = substr($$dataPt, $$dirInfo{DirStart}, $$dirInfo{DirLen}); $dataPt = \$buff; } } # set NewIPTCDigest data member unless IPTC is being deleted $$exifTool{NewIPTCDigest} = Digest::MD5::md5($$dataPt) if length $$dataPt; return $newData; } 1; # end __END__ =head1 NAME Image::ExifTool::WriteIPTC.pl - Write IPTC meta information =head1 SYNOPSIS This file is autoloaded by Image::ExifTool::IPTC. =head1 DESCRIPTION This file contains routines to write IPTC metadata, plus a few other seldom-used routines. =head1 AUTHOR Copyright 2003-2009, Phil Harvey (phil at owl.phy.queensu.ca) This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =head1 SEE ALSO L<Image::ExifTool::IPTC(3pm)|Image::ExifTool::IPTC>, L<Image::ExifTool(3pm)|Image::ExifTool> =cut
opf-attic/ref
tools/fits/0.5.0/tools/exiftool/perl/lib/Image/ExifTool/WriteIPTC.pl
Perl
apache-2.0
25,176
package OpenXPKI::Server::Database::Driver::DB2; use Moose; use utf8; with qw( OpenXPKI::Server::Database::Role::SequenceSupport OpenXPKI::Server::Database::Role::MergeEmulation OpenXPKI::Server::Database::Role::Driver ); =head1 Name OpenXPKI::Server::Database::Driver::DB2 - Driver for IBM DB2 databases =cut ################################################################################ # required by OpenXPKI::Server::Database::Role::Driver # # DBI compliant driver name sub dbi_driver { 'DB2' } # DSN string including all parameters. sub dbi_dsn { my $self = shift; return sprintf("dbi:%s:dbname=%s", $self->dbi_driver, $self->name, ); } # Additional parameters for DBI's connect() sub dbi_connect_params { } # Commands to execute after connecting sub dbi_on_connect_do { } # Parameters for SQL::Abstract::More sub sqlam_params { limit_offset => 'FetchFirst', # see SQL::Abstract::Limit source code } ################################################################################ # required by OpenXPKI::Server::Database::Role::Driver # sub sequence_create_query { my ($self, $dbi, $seq) = @_; return OpenXPKI::Server::Database::Query->new( string => "CREATE SEQUENCE $seq START WITH 0 INCREMENT BY 1 MINVALUE 0 NO MAXVALUE ORDER", ); } sub table_drop_query { my ($self, $dbi, $table) = @_; # TODO For DB2 check if table exists before dropping to avoid errors return OpenXPKI::Server::Database::Query->new( string => "DROP TABLE $table", ); } ################################################################################ # required by OpenXPKI::Server::Database::Role::SequenceSupport # sub nextval_query { my ($self, $seq) = @_; return "VALUES NEXTVAL FOR $seq"; } __PACKAGE__->meta->make_immutable; =head1 Description This class is not meant to be instantiated directly. Use L<OpenXPKI::Server::Database/new> instead. =cut
stefanomarty/openxpki
core/server/OpenXPKI/Server/Database/Driver/DB2.pm
Perl
apache-2.0
1,953
package # Date::Manip::TZ::pawall00; # Copyright (c) 2008-2014 Sullivan Beck. All rights reserved. # This program is free software; you can redistribute it and/or modify it # under the same terms as Perl itself. # This file was automatically generated. Any changes to this file will # be lost the next time 'tzdata' is run. # Generated on: Fri Nov 21 10:41:45 EST 2014 # Data version: tzdata2014j # Code version: tzcode2014j # This module contains data from the zoneinfo time zone database. The original # data was obtained from the URL: # ftp://ftp.iana.org/tz use strict; use warnings; require 5.010000; our (%Dates,%LastRule); END { undef %Dates; undef %LastRule; } our ($VERSION); $VERSION='6.48'; END { undef $VERSION; } %Dates = ( 1 => [ [ [1,1,2,0,0,0],[1,1,2,12,15,20],'+12:15:20',[12,15,20], 'LMT',0,[1900,12,31,11,44,39],[1900,12,31,23,59,59], '0001010200:00:00','0001010212:15:20','1900123111:44:39','1900123123:59:59' ], ], 1900 => [ [ [1900,12,31,11,44,40],[1900,12,31,23,44,40],'+12:00:00',[12,0,0], 'WFT',0,[9999,12,31,0,0,0],[9999,12,31,12,0,0], '1900123111:44:40','1900123123:44:40','9999123100:00:00','9999123112:00:00' ], ], ); %LastRule = ( ); 1;
nriley/Pester
Source/Manip/TZ/pawall00.pm
Perl
bsd-2-clause
1,294
% Frame number: 503 holdsAt( orientation( grp_ID0 )=117, 20120 ). holdsAt( appearance( grp_ID0 )=appear, 20120 ). % Frame number: 504 holdsAt( orientation( grp_ID0 )=124, 20160 ). holdsAt( appearance( grp_ID0 )=visible, 20160 ). % Frame number: 505 holdsAt( orientation( grp_ID0 )=135, 20200 ). holdsAt( appearance( grp_ID0 )=visible, 20200 ). % Frame number: 506 holdsAt( orientation( grp_ID0 )=139, 20240 ). holdsAt( appearance( grp_ID0 )=visible, 20240 ). % Frame number: 507 holdsAt( orientation( grp_ID0 )=139, 20280 ). holdsAt( appearance( grp_ID0 )=visible, 20280 ). % Frame number: 508 holdsAt( orientation( grp_ID0 )=139, 20320 ). holdsAt( appearance( grp_ID0 )=visible, 20320 ). % Frame number: 509 holdsAt( orientation( grp_ID0 )=139, 20360 ). holdsAt( appearance( grp_ID0 )=visible, 20360 ). % Frame number: 510 holdsAt( orientation( grp_ID0 )=139, 20400 ). holdsAt( appearance( grp_ID0 )=visible, 20400 ). % Frame number: 511 holdsAt( orientation( grp_ID0 )=139, 20440 ). holdsAt( appearance( grp_ID0 )=visible, 20440 ). % Frame number: 512 holdsAt( orientation( grp_ID0 )=139, 20480 ). holdsAt( appearance( grp_ID0 )=visible, 20480 ). % Frame number: 513 holdsAt( orientation( grp_ID0 )=139, 20520 ). holdsAt( appearance( grp_ID0 )=visible, 20520 ). % Frame number: 514 holdsAt( orientation( grp_ID0 )=139, 20560 ). holdsAt( appearance( grp_ID0 )=disappear, 20560 ). % Frame number: 990 holdsAt( orientation( grp_ID1 )=120, 39600 ). holdsAt( appearance( grp_ID1 )=appear, 39600 ). % Frame number: 991 holdsAt( orientation( grp_ID1 )=115, 39640 ). holdsAt( appearance( grp_ID1 )=visible, 39640 ). % Frame number: 992 holdsAt( orientation( grp_ID1 )=115, 39680 ). holdsAt( appearance( grp_ID1 )=visible, 39680 ). % Frame number: 993 holdsAt( orientation( grp_ID1 )=115, 39720 ). holdsAt( appearance( grp_ID1 )=visible, 39720 ). % Frame number: 994 holdsAt( orientation( grp_ID1 )=115, 39760 ). holdsAt( appearance( grp_ID1 )=visible, 39760 ). % Frame number: 995 holdsAt( orientation( grp_ID1 )=108, 39800 ). holdsAt( appearance( grp_ID1 )=visible, 39800 ). % Frame number: 996 holdsAt( orientation( grp_ID1 )=108, 39840 ). holdsAt( appearance( grp_ID1 )=visible, 39840 ). % Frame number: 997 holdsAt( orientation( grp_ID1 )=108, 39880 ). holdsAt( appearance( grp_ID1 )=visible, 39880 ). % Frame number: 998 holdsAt( orientation( grp_ID1 )=108, 39920 ). holdsAt( appearance( grp_ID1 )=visible, 39920 ). % Frame number: 999 holdsAt( orientation( grp_ID1 )=108, 39960 ). holdsAt( appearance( grp_ID1 )=visible, 39960 ). % Frame number: 1000 holdsAt( orientation( grp_ID1 )=108, 40000 ). holdsAt( appearance( grp_ID1 )=visible, 40000 ). % Frame number: 1001 holdsAt( orientation( grp_ID1 )=108, 40040 ). holdsAt( appearance( grp_ID1 )=visible, 40040 ). % Frame number: 1002 holdsAt( orientation( grp_ID1 )=108, 40080 ). holdsAt( appearance( grp_ID1 )=visible, 40080 ). % Frame number: 1003 holdsAt( orientation( grp_ID1 )=108, 40120 ). holdsAt( appearance( grp_ID1 )=visible, 40120 ). % Frame number: 1004 holdsAt( orientation( grp_ID1 )=108, 40160 ). holdsAt( appearance( grp_ID1 )=visible, 40160 ). % Frame number: 1005 holdsAt( orientation( grp_ID1 )=108, 40200 ). holdsAt( appearance( grp_ID1 )=visible, 40200 ). % Frame number: 1006 holdsAt( orientation( grp_ID1 )=112, 40240 ). holdsAt( appearance( grp_ID1 )=visible, 40240 ). % Frame number: 1007 holdsAt( orientation( grp_ID1 )=112, 40280 ). holdsAt( appearance( grp_ID1 )=visible, 40280 ). % Frame number: 1008 holdsAt( orientation( grp_ID1 )=112, 40320 ). holdsAt( appearance( grp_ID1 )=visible, 40320 ). % Frame number: 1009 holdsAt( orientation( grp_ID1 )=112, 40360 ). holdsAt( appearance( grp_ID1 )=visible, 40360 ). % Frame number: 1010 holdsAt( orientation( grp_ID1 )=112, 40400 ). holdsAt( appearance( grp_ID1 )=visible, 40400 ). % Frame number: 1011 holdsAt( orientation( grp_ID1 )=115, 40440 ). holdsAt( appearance( grp_ID1 )=visible, 40440 ). % Frame number: 1012 holdsAt( orientation( grp_ID1 )=115, 40480 ). holdsAt( appearance( grp_ID1 )=visible, 40480 ). % Frame number: 1013 holdsAt( orientation( grp_ID1 )=118, 40520 ). holdsAt( appearance( grp_ID1 )=visible, 40520 ). % Frame number: 1014 holdsAt( orientation( grp_ID1 )=118, 40560 ). holdsAt( appearance( grp_ID1 )=visible, 40560 ). % Frame number: 1015 holdsAt( orientation( grp_ID1 )=118, 40600 ). holdsAt( appearance( grp_ID1 )=disappear, 40600 ).
JasonFil/Prob-EC
dataset/strong-noise/18-LeftBag_PickedUp/lbpugtAppearenceGrp.pl
Perl
bsd-3-clause
4,504
#! /usr/bin/env perl use Config; # Check that the perl implementation file modules generate paths that # we expect for the platform use File::Spec::Functions qw(:DEFAULT rel2abs); if (!$ENV{CONFIGURE_INSIST} && rel2abs('.') !~ m|\\|) { die <<EOF; ****************************************************************************** This perl implementation doesn't produce Windows like paths (with backward slash directory separators). Please use an implementation that matches your building platform. This Perl version: $Config{version} for $Config{archname} ****************************************************************************** EOF } 1;
jens-maus/amissl
openssl/Configurations/windows-checker.pm
Perl
bsd-3-clause
653
package Moose::Manual::Construction; # ABSTRACT: Object construction (and destruction) with Moose =pod =head1 NAME Moose::Manual::Construction - Object construction (and destruction) with Moose =head1 VERSION version 2.0602 =head1 WHERE'S THE CONSTRUCTOR? B<Do not define a C<new()> method for your classes!> When you C<use Moose> in your class, your class becomes a subclass of L<Moose::Object>. The L<Moose::Object> provides a C<new()> method for your class. If you follow our recommendations in L<Moose::Manual::BestPractices> and make your class immutable, then you actually get a class-specific C<new()> method "inlined" in your class. =head1 OBJECT CONSTRUCTION AND ATTRIBUTES The Moose-provided constructor accepts a hash or hash reference of named parameters matching your attributes (actually, matching their C<init_arg>s). This is just another way in which Moose keeps you from worrying I<how> classes are implemented. Simply define a class and you're ready to start creating objects! =head1 OBJECT CONSTRUCTION HOOKS Moose lets you hook into object construction. You can validate an object's state, do logging, customize construction from parameters which do not match your attributes, or maybe allow non-hash(ref) constructor arguments. You can do this by creating C<BUILD> and/or C<BUILDARGS> methods. If these methods exist in your class, Moose will arrange for them to be called as part of the object construction process. =head2 BUILDARGS The C<BUILDARGS> method is called as a class method I<before> an object is created. It will receive all of the arguments that were passed to C<new()> I<as-is>, and is expected to return a hash reference. This hash reference will be used to construct the object, so it should contain keys matching your attributes' names (well, C<init_arg>s). One common use for C<BUILDARGS> is to accommodate a non-hash(ref) calling style. For example, we might want to allow our Person class to be called with a single argument of a social security number, C<< Person->new($ssn) >>. Without a C<BUILDARGS> method, Moose will complain, because it expects a hash or hash reference. We can use the C<BUILDARGS> method to accommodate this calling style: around BUILDARGS => sub { my $orig = shift; my $class = shift; if ( @_ == 1 && !ref $_[0] ) { return $class->$orig( ssn => $_[0] ); } else { return $class->$orig(@_); } }; Note the call to C<< $class->$orig >>. This will call the default C<BUILDARGS> in L<Moose::Object>. This method takes care of distinguishing between a hash reference and a plain hash for you. =head2 BUILD The C<BUILD> method is called I<after> an object is created. There are several reasons to use a C<BUILD> method. One of the most common is to check that the object state is valid. While we can validate individual attributes through the use of types, we can't validate the state of a whole object that way. sub BUILD { my $self = shift; if ( $self->country_of_residence eq 'USA' ) { die 'All US residents must have an SSN' unless $self->has_ssn; } } Another use of a C<BUILD> method could be for logging or tracking object creation. sub BUILD { my $self = shift; debug( 'Made a new person - SSN = ', $self->ssn, ); } The C<BUILD> method is called with the hash reference of the parameters passed to the constructor (after munging by C<BUILDARGS>). This gives you a chance to do something with parameters that do not represent object attributes. sub BUILD { my $self = shift; my $args = shift; $self->add_friend( My::User->new( user_id => $args->{user_id}, ) ); } =head3 BUILD and parent classes The interaction between multiple C<BUILD> methods in an inheritance hierarchy is different from normal Perl methods. B<You should never call C<< $self->SUPER::BUILD >>>, nor should you ever apply a method modifier to C<BUILD>. Moose arranges to have all of the C<BUILD> methods in a hierarchy called when an object is constructed, I<from parents to children>. This might be surprising at first, because it reverses the normal order of method inheritance. The theory behind this is that C<BUILD> methods can only be used for increasing specialization of a class's constraints, so it makes sense to call the least specific C<BUILD> method first. Also, this is how Perl 6 does it. =head1 OBJECT DESTRUCTION Moose provides a hook for object destruction with the C<DEMOLISH> method. As with C<BUILD>, you should never explicitly call C<< $self->SUPER::DEMOLISH >>. Moose will arrange for all of the C<DEMOLISH> methods in your hierarchy to be called, from most to least specific. Each C<DEMOLISH> method is called with a single argument. In most cases, Perl's built-in garbage collection is sufficient, and you won't need to provide a C<DEMOLISH> method. =head2 Error Handling During Destruction The interaction of object destruction and Perl's global C<$@> and C<$?> variables can be very confusing. Moose always localizes C<$?> when an object is being destroyed. This means that if you explicitly call C<exit>, that exit code will be preserved even if an object's destructor makes a system call. Moose also preserves C<$@> against any C<eval> calls that may happen during object destruction. However, if an object's C<DEMOLISH> method actually dies, Moose explicitly rethrows that error. If you do not like this behavior, you will have to provide your own C<DESTROY> method and use that instead of the one provided by L<Moose::Object>. You can do this to preserve C<$@> I<and> capture any errors from object destruction by creating an error stack. =head1 AUTHOR Moose is maintained by the Moose Cabal, along with the help of many contributors. See L<Moose/CABAL> and L<Moose/CONTRIBUTORS> for details. =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2012 by Infinity Interactive, Inc.. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =cut __END__
leighpauls/k2cro4
third_party/perl/perl/vendor/lib/Moose/Manual/Construction.pod
Perl
bsd-3-clause
6,143
# Part of get-flash-videos. See get_flash_videos for copyright. package FlashVideo::Site::Xvideos; use strict; use base 'FlashVideo::Site::Xnxx'; 1;
njtaylor/get-flash-videos
lib/FlashVideo/Site/Xvideos.pm
Perl
apache-2.0
151