Menu
  • HOME
  • TAGS

Backslash before a subroutine call

Tag: perl,reference,subroutine

As I was understanding the difference between [] and \ in references,I used both on subroutine the former was fine but when I tried later I thought it should give error but the below program in perl

#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;

my @b;
for my $i ( 0 .. 10 ) {
    $b[$i] = \somefunc($i);

}
print Dumper( \@b );

sub somefunc {
    my $n = shift;
    my ( @a, $k );
    for my $j ( 11 .. 13 ) {
        $k = $n * $j;
        push( @a, $k );
    }
    print "a: @a \n";
    return @a;
}

gives output as :

a: 0 0 0 
a: 11 12 13 
a: 22 24 26 
a: 33 36 39 
a: 44 48 52 
a: 55 60 65 
a: 66 72 78 
a: 77 84 91 
a: 88 96 104 
a: 99 108 117 
a: 110 120 130 
$VAR1 = [
      \0,
      \13,
      \26,
      \39,
      \52,
      \65,
      \78,
      \91,
      \104,
      \117,
      \130
    ];

I was unable to understand the output.Need explanation.

Best How To :

What is happening here is:

You are returning an array from somefunc.

But you are assigning it to a scalar. What this is effectively doing therefore, is simply putting the last value in the array, into the scalar value.

my $value =  ( 110, 120, 130 );
print $value;

When you do this - $value is set to the last value in the array. This is what's actually happening in your code. See for example perldata:

List values are denoted by separating individual values by commas (and enclosing the list in parentheses where precedence requires it): (LIST)

In a context not requiring a list value, the value of what appears to be a list literal is simply the value of the final element, as with the C comma operator. For example,

@foo = ('cc', '-E', $bar);

assigns the entire list value to array @foo, but

foo = ('cc', '-E', $bar);

assigns the value of variable $bar to the scalar variable $foo. Note that the value of an actual array in scalar context is the length of the array; the following assigns the value 3 to $foo:

@foo = ('cc', '-E', $bar); $foo = @foo; # $foo gets 3

It's this latter case that's often the gotcha, because it's a list in a scalar context.

And in your example - the backslash prefix denotes 'reference to' - which is largely meaningless because it's a reference to a number.

But for a scalar, it might be more meaningful:

my $newvalue = "fish"; 
my $value =  ( 110, 120, 130, \$newvalue );
print Dumper $value;

$newvalue = 'barg'; 
print Dumper $value;

Gives:

$VAR1 = \'fish';
$VAR1 = \'barg';

That's why you're getting the results. Prefix with the slash indicates that you're getting a reference to the result, not a reference to the sub. Reference to 130 isn't actually all that meaningful.

Normally, when doing the assignment above - you'd get a warning about Useless use of a constant (110) in void context but this doesn't apply when you've got a subroutine return.

If you wanted to insert a sub reference, you'd need to add &, but if you just want to insert the returned array by reference - you either need to:

$b[$i] = [somefunc($i)]

Or:

return \@a;

Why this exclusion not working for long sentences?

text-processing,perl

You're using the wrong syntax: [] is used to match a character class, while here you're trying to match a number of occurences of ., which can be done using {}: perl -ne 'print unless /.{240,}/' input.txt > output.txt Also, as suggested by salva in the comments, the pattern can...

Reducing code verbosity and efficiency

perl

There is a famous quote: "Premature optimisation is the root of all evil" - Donald Knuth It is almost invariably the case that making code more concise really doesn't make much difference to the efficiency, and can cause significant penalties to readability and maintainability. Algorithm is important, code layout ......

Perl & Regex within Windows CMD Line

regex,windows,perl

If I understand correctly, you want to pull out all of the matches from an entire file, and write those results to a separate file. This will work if the below results are what you're after. I don't have a Windows box to test on, but this should work (you...

C++ - back to start of loop without checking the condition

c++,perl,loops,redo

There is no redo keyword for going back to the start of a loop, but there's no reason you couldn't do it with goto. (Oh I feel so dirty recommending goto...) int tries = 0; for(int i=0; i<10; ++i) { loop_start: bool ok = ((i+tries)%3==0); if(ok) { ++tries; goto loop_start;...

Create unicode character with pack

perl,unicode

Why do I get ff and not c3bf when using pack ? This is because pack creates a character string, not a byte string. > perl -MDevel::Peek -e 'Dump(pack("U", 0xff));' SV = PV(0x13a6d18) at 0x13d2ce8 REFCNT = 1 FLAGS = (PADTMP,POK,READONLY,pPOK,UTF8) PV = 0xa6d298 "\303\277"\0 [UTF8 "\x{ff}"] CUR =...

Perl Debugging Using Flags

perl,debugging,script-debugging

In perl, compile time is also run time. So there's really not a great deal of advantage in using #define type statements. My usual trick is: my $debug = 0; $debug += scalar grep ( "-d", @ARGV ); (GetOpt is probably honestly a better plan though) And then use: print...

Plain text emails displayed as attachment on some email clients

perl,email,attachment,mime,plaintext

I think this is the closes thing you're going to get to an answer The documentation for MIME::Lite says this MIME::Lite is not recommended by its current maintainer. There are a number of alternatives, like Email::MIME or MIME::Entity and Email::Sender, which you should probably use instead. MIME::Lite continues to accrue...

Check for decimal point and add it at the end if its not there using awk/perl

regex,perl,shell,awk

In awk Just sub for those fields awk -F, -vOFS="," '{sub(/^[^\.]+$/,"&.",$6);sub(/^[^\.]+$/,"&.",$11)}1' file or sed sed 's/^\(\([^,]*,\)\{5\}[^.,]\+\),/\1./;s/^\(\([^,]*,\)\{10\}[^.,]\+\),/\1./' file ...

What does this horribly ugly (yet somehow secretly beautiful) Perl code do?

perl,formatting,deobfuscation

Passing the code to Google returns this page that explains qrpff is a Perl script created by Keith Winstein and Marc Horowitz of the MIT SIPB. It performs DeCSS in six or seven lines. The name itself is an encoding of "decss" in rot-13. See also qrpff explained....

Opening multiple files in perl array

arrays,perl

You just need to enclose the code that handles a single file in a loop that iterates over all of the log files You should also reconsider the amount of comments that you use. It is far better to write your code and choose identifiers so that the behaviour is...

Perl would I use fc over uc?

perl

fc is used for case-insensitive comparisons. uc($a) cmp uc($b) # XXX lc($a) cmp lc($b) # XXX fc($a) cmp fc($b) # ok An example where this makes a difference: lc uc fc -- -- -- -- ss ss SS ss SS ss SS ss ß ß SS ss ẞ ß ẞ...

Windows/Linux child process STDIN differences

linux,windows,perl,process,stdin

This isn't a Windows verus Linux thing. You simply picked two awful examples. type con reads from the console, not from STDIN. This can be seen using type con <nul. cat is extremely unusual. Buffering, on either system, is completely up to the individual application, but almost all applications work...

Is a Java class variable a reference to a class object?

java,class,object,reference

obj is a reference to the object of type foo , your understanding is correct. In line 1 , JVM creates a new instance (ojbect) of type foo (new memory is allocated in the heap) , and obj now stores the reference to that memory location, lets assume that memory...

passing arguments via reference and pointer C++

c++,function,pointers,reference

Yes. There's no copy anywhere as you're either using pointers or references when you “pass” the variable from one place to another, so you're actually using the same variable everywhere. In g(), you return a reference to z, then in f() you keep this reference to z. Moreover, when you...

Counting occurrences of a word in a string in Perl

regex,perl

I get the correct number - 6 - for the first string However your method is wrong, because if you count the number of pieces you get by splitting on the regex pattern it will give you different values depending on whether the word appears at the beginning of the...

Perl: Using Text::CSV to print AoH

arrays,perl,csv

Pretty fundamentally - CSV is an array based data structure - it's a vaguely enhanced version of join. But the thing you need for this job is print_hr from Text::CSV. First you need to set your header order: $csv->column_names (@names); # Set column names for getline_hr () Then you can...

Deleting upto a line

bash,perl,shell,sed,scripting

Try this: grep -oE '[0-9.-]+$' file or awk '{print $NF}' file ...

Parameters to use in a referenced function c++

c++,pointers,reference

Your code makes no sense, why are you passing someStruct twice? For the reference part, you should have something like: void names(someStruct &s) { // <<<< Pass struct once as a reference cout << "First Name: " << "\n"; cin >> s.firstname; cout << "Last Name: " << "\n"; cin...

System.Windows.Interactivity must be referenced in the main project

c#,wpf,dll,reference

System.Windows.Interactivity.dll is not in the GAC, so .Net doesn't know where to find it. By adding a reference to your main project, you make the build system copy the DLL to the output folder. This lets the runtime find it....

-M Script start time minus file modification time, in days

perl,perldoc

I think this explains what you are seeing perl -E 'say "START TIME",$^T; qx(touch $_), sleep(5), say -M for "/tmp/file"; say "STAT ON FILE", (stat(_))[9]' output when I ran it START TIME1434460114 0 STAT ON FILE1434460114 1) script starts $^T is set to 1434460114 2) almost immediately the file "/tmp/file"...

unable to understand qr interpolation

regex,perl

The chapter of the Perl documentation that deals with this is called perlre. In the extended pattern matching section it explains this. Starting in Perl 5.14, a "^" (caret or circumflex accent) immediately after the "?" is a shorthand equivalent to d-imsx . Flags (except "d" ) may follow the...

How to copy matches from an extremely large file if it contains no newlines?

python,linux,bash,perl,grep

#!/usr/bin/perl use strict; use warnings; use constant BLOCK_SIZE => 64*1024; my $buf = ""; my $searching = 1; while (1) { my $rv = read(\*STDIN, $buf, BLOCK_SIZE, length($buf)); die($!) if !defined($rv); last if !$rv while (1) { if ($searching) { my $len = $buf =~ m{\[(?:a|\z)} ? $-[0] : length($buf);...

Can't locate module(s) using Mojo::DOM

perl,dom,mojolicious,mojo

It's very difficult to debug a single long chained statement like that, and you're much better off splitting it into individual steps Passing a parameter to the dom method is the same as calling find with that parameter on the DOM object. find returns a Mojo::Collection, which makes sense as...

Reading from DATA file handle

performance,perl

I did some benchmarking against three methods. I used an external file for reading (instead of __DATA__). The file consisted of 3 million lines of the exact data you were using. The methods are slurping the file, reading the file line-by line, and using Storable as Sobrique mentioned above. Each...

problems copying shared hash in perl threads

multithreading,perl

Two threads are iterating over the same hash at the same time, so they are both changing its iterator. You need to make sure that no more than one thread uses the hash's iterator at a time. I'd remove all those :shared and use Thread::Queue::Any....

Python: how to reference values in a def

python,reference,return

You don't you need to return them def example(value1, value2): value1 += 2 value2 += 4 return (value1, value2) >>> value1 = 0 >>> value2 = 0 >>> value1, value2 = example(value1, value2) >>> print(value1, value2) 2 4 You can only do what you are asking if the passed-in type...

Perl : Display perl variable awk sed echo

perl

You can do that using a Perl regex pattern my $calculate; ($calculate = $1) =~ tr~,~/~ if $value =~ /SP=[^:]*:([^;]*)/; ...

return reference of static member variable c++

c++,reference,static

If POS is declared static then its lifetime is the lifetime of the program, and so returning a reference to it is safe.

Perl - an array content

arrays,perl

You can use grep to go through the array one at a time and see if any match: if ( grep $file ~= /\Q.$_\z/, @array ) { Or join the array elements into a single regex: my @array = qw(avi mp4 mov); my $selected_extensions = qr/^\.(?:@{[ join '|', map quotemeta,...

Version-dependent fallback code

perl

Many recent features are not forward-compatible. As you've seen, you'll get compile-time errors using a feature that is too new for the version of perl you are running. Using block-eval won't help, because the contents of the block need to be valid for the current perl interpreter. You are on...

Why Filter::Indent::HereDoc complain when blank line in middle of HereDoc

perl,heredoc

The documentation says: If there is no terminator string (so the here document stops at the first blank line), then enough whitespace will be stripped out so that the leftmost character of the document will be flush with the left margin, e.g. print <<; Hello, World! # This will print:...

Creating a sequence of unique random digits

arrays,perl,foreach,unique

To generate a list of four unique non-zero decimal digits, use shuffle from List::Util and pick the first four Like this use strict; use warnings; use 5.010; use List::Util 'shuffle'; my @unique = (shuffle 1 .. 9)[0..3]; say "@unique"; output 8 5 1 4 There's no need to seed the...

Capture tee's argument inside piped Perl execution

perl,unix

The short answer is - you can't. tee is a separate process with it's own arguments. There is no way to access these arguments from that process. (well, I suppose you could run ps or something). The point of tee is to take STDOUT write some of it to a...

calling cgi script from other cgi script

perl,cgi

A CGI program normally expects to fetch the parameter values from the environment variable QUERY_STRING. Passing parameter values on the command line is a debugging facility, and works only when the program is run from the command prompt You could try something like this my $result = do { local...

Regex in Perl Uninitialized $1

regex,perl

$1 is the value captured by the first capture (()), but you have no captures in your pattern. Fix: /(?<=File `..\/)(.*)(?=')/ Simplified: m{File `../(.*)'} More robust: m{File `../([^']*)'} ...

How to extract some text from an HTML doc using Web::Query

perl

The dot selector denotes class selections, which is not what you intend for the second div and h3. For these you want descendant. The correct syntax is; my $subject = $parts->find( 'div.subject > div > h3' )->text; # Which outputs # subjectfinal $VAR1 = '@if version_after macro is illogical'; For...

How to pass a hash as optional argument to -M in command line

perl,hash,package,command-line-interface

Looking at perlrun use: perl -Mfeature=say "-Mconstant {c1 => 'foo', c2 => 'bar'}" -e"say c1,c2" ...

How to match and remove the content preceding it from a file in unix [closed]

mysql,perl,sed,solaris

with GNU sed sed -n '1,/-- Final view structure for view `view_oss_user`/p' this will print lines from 1 till pattern found, others will not be printed or if you want to exclude pattern line then sed -n '1,/-- Final view structure for view `view_oss_user`/p' | sed '$d' ...

Command line arguments in Perl

perl

$! and $_ are global variables. For more information you can read here $_ The default input and pattern-searching space $! If used in a numeric context, yields the current value of the errno variable, identifying the last system call error. If used in a string context, yields the corresponding...

how to print all the lines of a text file from hash - perl

perl

You have while (my $line =<$fh>) which reads a single record via $fh. The default input record separator in Perl is "\n" meaning you are reading the file line-by-line. By definition, a single line has a single line-terminator. chomp ($line); then removes this single "\n" from the string in $line....

Looping variables

perl,scripting

As per my comment, most of the functionality of your program is provided by the Math::Vector::Real module that you're already using It looks like you want the angle in degrees between successive pairs of 3D vectors in your file. This code creates vectors from each line in the file until...

Difficulties initializing an array in Perl

arrays,perl,hash

$dec_res->{repositories} is clearly an array It isn't. It is an array reference. but @repos is not? It is an array. You are creating a list that is one item long, and that item is the array reference. You then assign the list to the array, so the array holds...

Get ISO DateTime with only core modules in Perl?

perl

This is simple with the POSIX function strftime: use POSIX qw( strftime ); print strftime "%Y-%m-%d %H:%M:%S", localtime; POSIX has been core since 5.0....

Find numbers in a file and change their value with perl

regex,perl

You can just match the numbers that are less than one.. and replace with 1: perl -pe 's/\b0\.\d+/1/g' file See DEMO...

Watching a variable in python?

python,reference

A raw int will not work, but as k4vin points, out, any other type of object that can be referenced, will. We can demonstrate this with a list that contains the count, as k4vin did: class Watcher(object): def __init__(self, to_watch): self.to_watch = to_watch def print_current_value(self): print self.to_watch i = 0...

Perl: Multiply loops, 1 hash and regex

arrays,regex,perl,hash,perl-data-structures

you need to append the file when you output meaning use ">>" instead of ">" which will overwrite the file. system("chage -l $_ >> $pwdsett_dump") as you are running it in loop you are overwriting each time the loop executes. Use: foreach (@Usernames) { system("chage -l $_ >> $pwdsett_dump") }...

Access to reference in member variable discards constness

c++,c++11,reference,compiler-errors,const

Yes, this is correct behaviour. The type of ref is Foo &. Adding const to a reference type1 does nothing—a reference is already immutable, anyway. It's like having a member int *p. In a const member function, its type is treated as int * const p, not as int const...

Perl XML-RPC output format/schema

php,xml,perl,rpc,xml-rpc

Your own XML is quite different. The contents of the parameter are correct <value> <struct> <member> <name>utilisateur</name> <value> <string>user</string> </value> </member> <member> <name>motdePasse</name> <value> <string>pass</string> </value> </member> </struct> </value> but the version sent by the PHP code has this wrapped in a named structure, like this <value> <struct> <member>...

Taking multiple header (rows matching condition) and convert into a column

bash,perl,command-line,awk,sed

In awk awk -F, 'NF==1{a=$0;next}{print a","$0}' file Checks if the number of fields is 1, if it is it sets a variable to that and skips the next block. For each line that doesn't have 1 field, it prints the saved variable and the line And in sed sed -n...

Using a stored integer as a cell reference

excel,excel-vba,reference

You have to find a suitable formula for entering in the target cell. Then you would build such formula with string concatenation, etc., for entering it via VBA. One option for the formula is to use OFFSET, as in =SUM(OFFSET($A$1,D3-1,COLUMN()-1):OFFSET($A$1,ROW()-3-1,COLUMN()-1)) This sums all values from Cell1 to Cell2, in the...