End of line anchor $ match even there is extra trailing \n in matched string, so we use \Z instead of $
For example
^\w+$ will match the string abcd\n but ^\w+\Z is not
How about \A and when to use?
HELLO ALL,
I USED THE BELOW CODE FOR CAPTURING THE OUTPUT (BELOW IN lines) IN A FILE "my_output.txt" BUT FAILED TO CAPTURE.
**************output***************
inside value loop
------------------------------------------------------------
Server listening on UDP port 5001
Receiving 1470 byte datagrams
UDP buffer size: 108 KByte (default)
------------------------------------------------------------
[ 3] local 192.168.16.2 port 5001 connected with 192.168.16.1 port 3189
[ ID] Interval Transfer Bandwidth Jitter Lost/Total Datagrams
[ 3] 0.0- 5.0 sec 2.14 MBytes 3.61 Mbits/sec 0.369 ms 0/ 1528 (0%)
inside value loop3
clue1
clue2
inside value loop4
one iperf completed
***************************************
however when i enabled the local *STDOUT; in below code then i could see the above output on command prompt display (ofcourse server is sending some data).
could anybody suggest me how can i capture the o/p in a file intended?
below is the code i am using ..
my $file = 'my_output.txt';
use Win32::Process;
print"inside value loop\n";
# redirect stdout to a file
#local *STDOUT;
open STDOUT, '>', $file
or die "can't redirect STDOUT to <$file> $!";
Win32::Process::Create(my $ProcessObj,
"D:\\IOT_AUTOMATION_UTILITY\\_SATURDAY_09-04-10\\adb_cmd.bat",
"adb shell /data/app/iperf -u -s -p 5001",
0,
NORMAL_PRIORITY_CLASS,
".") || die ErrorReport();
#$alarm_time = $IPERF_RUN_TIME+10; #20sec
#$ProcessObj->Wait(40);
#print"inside value loop2\n";
#sleep $alarm_time;
sleep 40;
$ProcessObj->Kill(0);
sub ErrorReport{
print Win32::FormatMessage( Win32::GetLastError() );
}
/rocky
Hi If there is no special character(such as white space, : etc) between firstname and lastname.
Then how to split the Chinese characters below.
use strict;
use warnings;
use Data::Dumper;
my $fh = \*DATA;
my $fname; # ? ;
my $lname; # ??;
while(my $name = <$fh>)
{
$name =~ ??? ;
print $fname"/n";
print $lname;
}
__DATA__
???
Output
?
??
I am in search of who specifically to contact at Sybase regarding Advantage Database Server's DBI driver, specifically DBD::Advantage.
The only reference I can find is to one 'lancesc' in the README, but there are no references to a contact email, CPAN author etc. Inadvertantly I happened upon one StackOverflow user lancesc here.
Would anyone happen to know who to contact regarding this? I do wish this was on CPAN.
I've found a small bug regarding column quoting in the sql parser that they'd likely prefer to be made aware of. There are also several questions I have for them regarding failing functionality.
I am trying to add all the elements in array using push . then i stored into another file
but begining of file i am seeing one whitespeace in every thing ..
What is the issue .. any one before face this issue .
open FILE , "a.txt"
while (<FILE>)
{
my $temp =$_;
push @array ,$temp;
}
close(FILE);
open FILE2, "b.txt";
print FILE2 "@array";
close FILE2;
In emacs cperl-mode, ternary operators are not treated specially. If you break them over multiple lines, cperl-mode simply indents each line the same way it indents any continued statement, like this:
$result = ($foo == $bar) ? 'result1' :
($foo == $baz) ? 'result2' :
($foo == $qux) ? 'result3' :
($foo == $quux) ? 'result4' :
fail_result;
This is not very readable. Is there some way that I can convince cperl-mode indent like this?
$result = ($foo == $bar) ? 'result1' :
($foo == $baz) ? 'result2' :
($foo == $qux) ? 'result3' :
($foo == $quux) ? 'result4' :
fail_result;
By the way, code example from this question.
I'm parsing some big log files and have some very simple string matches for example
if(m/Some String Pattern/o){
#Do something
}
It seems simple enough but in fact most of the matches I have could be against the start of the line, but the match would be "longer" for example
if(m/^Initial static string that matches Some String Pattern/o){
#Do something
}
Obviously this is a longer regular expression and so more work to match. However I can use the start of line anchor which would allow an expression to be discarded as a failed match sooner.
It is my hunch that the latter would be more efficient. Can any one back me up/shoot me down :-)
Hi,
This code works:
my $href = shift @_; # get reference to hash
my %h = %{$href}; # dereference hash
This one does not:
my %h = %{shift @_};
As well as this one:
my %h = ${$_[0]}
Why?
I'm trying to understand the behavior of the fields pragma, which I find poorly documented, regarding fields prefixed with underscores. This is what the documentation has to say about it:
Field names that start with an underscore character are made private to the class and are not visible to subclasses. Inherited fields can be overridden but will generate a warning if used together with the -w switch.
This is not consistent with its actual behavior, according to my test, below. Not only are _-prefixed fields visible within a subclass, they are visible within foreign classes as well (unless I don't get what 'visible' means). Also, directly accessing the restricted hash works fine.
Where can I find more about the behavior of the fields pragma, short of going at the source code?
{
package Foo;
use strict;
use warnings;
use fields qw/a _b __c/;
sub new {
my ( $class ) = @_;
my Foo $self = fields::new($class);
$self->a = 1; $self->b = 2; $self->c = 3;
return $self;
}
sub a : lvalue { shift->{a} }
sub b : lvalue { shift->{_b} }
sub c : lvalue { shift->{__c} }
}
{
package Bar;
use base 'Foo';
use strict;
use warnings;
use Data::Dumper;
my $o = Bar->new;
print Dumper $o; ##$VAR1 = bless({'_b' => 2, '__c' => 3, 'a' => 1}, 'Foo');
$o->a = 4; $o->b = 5; $o->c = 6;
print Dumper $o; ##$VAR1 = bless({'_b' => 5, '__c' => 6, 'a' => 4}, 'Foo');
$o->{a} = 7; $o->{_b} = 8; $o->{__c} = 9;
print Dumper $o; ##$VAR1 = bless({'_b' => 8, '__c' => 9, 'a' => 7}, 'Foo');
}
I have long regexp with two complicated subpatters inside. How i can match that subpatterns in any order?
Simplified example:
/(apple)?\s?(banana)?\s?(orange)?\s?(kiwi)?/
and i want to match both of
apple banana orange kiwi
apple orange banana kiwi
It is very simplified example. In my case banana and orange is long complicated subpatterns and i don't want to do something like
/(apple)?\s?((banana)?\s?(orange)?|(orange)?\s?(banana)?)\s?(kiwi)?/
Is it possible to group subpatterns like chars in character class?
UPD Real data as requested:
14:24 26,37 Mb
108.53 01:19:02 06.07
24.39 19:39
46:00
my strings much longer, but it is significant part. Here you can see two lines what i need to match.
First has two values: length (14 min 24 sec) and size 26.37 Mb.
Second one has three values but in different order: size 108.53 Mb, length 01 h 19 m 02 s and date June, 07
Third one has two size and length
Fourth has only length
There are couple more variations and i need to parse all values.
I have a regexp that pretty close except i can't figure out how to match patterns in different order without writing it twice.
(?<size>\d{1,3}\[.,]\d{1,2}\s+(?:Mb)?)?\s?
(?<length>(?:(?:01:)?\d{1,2}:\d{2}))?\s*
(?<date>\d{2}\.\d{2}))?
NOTE: that is only part of big regexp that forks fine already.
$client = IO::Socket::SSL->new("pilot-payflopro.paypal.com:443");
my IO::Socket::SSL::errstr() is
failederror:00000000:lib(0):func(0):reason(0)
my $! is 'invalid argument'
Has anyone run into this before?
I'm using the date plugin for Template::Toolkit (Template::Plugin::Date), it works well with datetimes (yyyy-mm-dd hh:mm:ss) pulled straight out of MySQL, but it will not work with dates (yyyy-mm-dd).
What's the simplest way to get date.format to accept dates (without modifying the sql query)?
Thanks.
I have some files that I'd like to delete the last newline if it is the last character in a file. 'od -c' shows me that the command I run does write the file with a trailing new line:
0013600 n t > \n
I've tried a few tricks with sed but the best I could think of isn't doing the trick:
sed -e '$s/\(.*\)\n$/\1/' abc
Any ideas how to do this?
I used csv2xls.pl to convert a text log into .xls format, and then I create a chart as in the following:
my $chart3 = $workbook->add_chart( type => 'line' , embedded => 1);
# Configure the series.
$chart3->add_series(
categories => '=Sheet1!$B$2:$B$64',
values => '=Sheet1!$C$2:$C$64',
name => 'Test data series 1',
);
# Add some labels.
$chart3->set_title( name => 'Bridge Rate Analysis' );
$chart3->set_x_axis( name => 'Packet Size ' );
$chart3->set_y_axis( name => 'BVI Rate' );
# Insert the chart into the main worksheet.
$worksheet->insert_chart( 'G2', $chart3 );
I can see the chart in the .xls file. However, all the data are in text format, not numeric, so the chart looks wrong.
How do I convert text into number before applying this create-chart function?
Also, how do I sort the .xls file before creating the chart?
Hi, I want to enable use Encode::HanExtra; on winxp environment. I can't find the package name HanExtra or Ecode-HanExtra in PPM GUI. Is there any alias name for it?
I've recently started to try to use Dist::Zilla for maintaining Path::Class. I added the [PodCoverageTests] plugin, and it's reporting some failures in the Path::Class::Entity class, which is the abstract base class for Path::Class::File and Path::Class::Dir.
What I'd like is some way to tell the testing code that Entity doesn't need docs, but its two derived classes do - even though the methods are only defined in the parent class. Anyone know some way to do that?
I'm trying to understand the behavior of the fields pragma, which I find poorly documented, regarding fields prefixed with underscores. This is what the documentation has to say about it:
Field names that start with an underscore character are made private to the class and are not visible to subclasses. Inherited fields can be overridden but will generate a warning if used together with the -w switch.
This is not consistent with its actual behavior, according to my test, below. Not only are _-prefixed fields visible within a subclass, they are visible within foreign classes as well (unless I don't get what 'visible' means). Also, directly accessing the restricted hash works fine.
Where can I find more about the behavior of the fields pragma, short of going at the source code?
{
package Foo;
use strict;
use warnings;
use fields qw/a _b __c/;
sub new {
my ( $class ) = @_;
my Foo $self = fields::new($class);
$self->a = 1; $self->b = 2; $self->c = 3;
return $self;
}
sub a : lvalue { shift->{a} }
sub b : lvalue { shift->{_b} }
sub c : lvalue { shift->{__c} }
}
{
package Bar;
use base 'Foo';
use strict;
use warnings;
use Data::Dumper;
my $o = Bar->new;
print Dumper $o; ##$VAR1 = bless({'_b' => 2, '__c' => 3, 'a' => 1}, 'Foo');
$o->a = 4; $o->b = 5; $o->c = 6;
print Dumper $o; ##$VAR1 = bless({'_b' => 5, '__c' => 6, 'a' => 4}, 'Foo');
$o->{a} = 7; $o->{_b} = 8; $o->{__c} = 9;
print Dumper $o; ##$VAR1 = bless({'_b' => 8, '__c' => 9, 'a' => 7}, 'Foo');
}
i have this code :
use strict;
use LWP::UserAgent;
use warnings;
my $ua = new LWP::UserAgent(agent => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.5) Gecko/20060719 Firefox/1.5.0.5');
$ua->proxy([qw(http https)] => 'http://59.39.92.148:1080');
my $response = $ua->get("http://www.google.com");
print $response->code,' ', $response->message,"\n";
is the mean of code " open www.google.com with sock proxy"?
pls explain for me .
Hi,
This code smells... how do I rewrite it better?
my $record;
eval {
while (
# undef $record here, so if getRecord() failed, nothing will be written
# in the reject file
do { undef $record; defined( $record = $dataFile->getRecord ) }
) {
$LT_DataFile->encode($record);
}
1;
};
if ( my $error = $@ ) {
$rejectFile->writeRecord( $error, $record );
}
Thanks.
I'm reading in some data from a file, manipulating it, and then overwriting it to the same file. Until now, I've been doing it like so:
open (my $inFile, $file) or die "Could not open $file: $!";
$retString .= join ('', <$inFile>);
...
close ($inFile);
open (my $outFile, $file) or die "Could not open $file: $!";
print $outFile, $retString;
close ($inFile);
However I realized I can just use the truncate function and open the file for read/write:
open (my $inFile, '+<', $file) or die "Could not open $file: $!";
$retString .= join ('', <$inFile>);
...
truncate $inFile, 0;
print $inFile $retString;
close ($inFile);
I don't see any examples of this anywhere. It seems to work well, but am I doing it correctly? Is there a better way to do this?
I'm trying to write a sub that takes a coderef parameter. My sub does some initialization, calls the coderef, then does some cleanup.
I need to call the coderef using the same context (scalar, list, void context) that my sub was called in. The only way I can think of is something like this:
sub perform {
my ($self, $code) = @_;
# do some initialization...
my @ret;
my $ret;
if (not defined wantarray) {
$code->();
} elsif (wantarray) {
@ret = $code->();
} else {
$ret = $code->();
}
# do some cleanup...
if (not defined wantarray) {
return;
} elsif (wantarray) {
return @ret;
} else {
return $ret;
}
}
Obviously there's a good deal of redundancy in this code. Is there any way to reduce or eliminate any of this redundancy?
EDIT I later realized that I need to run $code->() in an eval block so that the cleanup runs even if the code dies. Adding eval support, and combining the suggestions of user502515 and cjm, here's what I've come up with.
sub perform {
my ($self, $code) = @_;
# do some initialization...
my $w = wantarray;
return sub {
my $error = $@;
# do some cleanup...
die $error if $error; # propagate exception
return $w ? @_ : $_[0];
}->(eval { $w ? $code->() : scalar($code->()) });
}
This gets rid of the redundancy, though unfortunately now the control flow is a little harder to follow.
I have a handful of DBIx::Class::Core objects that model various database tables.
For some of those models (those that have a 'queue' column), I have another class inject subs (basically, to 'move' the model object along it's queue states).
I'd like to also have that class inject has_many relationships ala
class($name)->has_many('queue_history','MySchema::Result::QueueHistory',
{ 'foreign.record_id'=>'self.id' },
{ where => { type => $name }} );
but I can't seem to get the relationships to register properly (keep getting "No Such Relationship" errors - however, when calling the relationship method on the sources provides back the relationship).
Any clues as to what's wrong?
I have to build unit tests for in environment with a very old version of Test::More (perl5.8 with $Test::More::VERSION being '0.80') which predates the addition of done_testing().
Upgrading to newer Test::More is out of the question for practical reasons. And I am trying to avoid using no_tests - it's generally a bad idea not catching when your unit test dies prematurely.
What is the most idiomatic way of running a configurable amount of tests, assuming no no_tests or done_testing() is used?
Details:
My unit tests usually take the form of:
use Test::More;
my @test_set = (
[ "Test #1", $param1, $param2, ... ]
,[ "Test #1", $param1, $param2, ... ]
# ,...
);
foreach my $test (@test_set) {
run_test($test);
}
sub run_test {
# $expected_tests += count_tests($test);
ok(test1($test)) || diag("Test1 failed");
# ...
}
The standard approach of use Test::More tests => 23; or BEGIN {plan tests => 23} does not work since both are obviously executed before @tests is known.
My current approach involves making @tests global and defining it in the BEGIN {} block as follows:
use Test::More;
BEGIN {
our @test_set = (); # Same set of tests as above
my $expected_tests = 0;
foreach my $test (@tests) {
my $expected_tests += count_tests($test);
}
plan tests = $expected_tests;
}
our @test_set; # Must do!!! Since first "our" was in BEGIN's scope :(
foreach my $test (@test_set) { run_test($test); } # Same
sub run_test {} # Same
I feel this can be done more idiomatically but not certain how to improve. Chief among the smells is the duplicate our @test_test declarations - in BEGIN{} and after it.