I have code to print out the first 9 squared numbers:
#!/usr/local/bin/perl
for($i=1;$i<10 ;$i++ )
{
printf $i^2 . "\n";
}
but for some reason this just outputs 30167451011. How do I properly square a number?
To square you have to use $i**2
#!/usr/local/bin/perl
for ( my $i = 1; $i < 10; $i++ ) {
print $i**2 . "\n";
}
This will output:
1
4
9
16
25
36
49
64
81
To explain what happened in the original code, you need to know 3 things: first, ^ is the XOR operator in perl, because it is the XOR operator in C.
1 ^ 2 = 3
2 ^ 2 = 0
3 ^ 2 = 1
4 ^ 2 = 6
...
Second, the ^ operator has lower precedence than the string concatenation operator . so $i^2 . "\n" is equivalent to $i ^ (2 . "\n")
Third, perl converts between strings and numbers as necessary. The . operator requires strings on both sides, so the 2 is converted to "2" and concatenated with the "\n" to become the string "2\n".
Then the ^ operator requires numbers on both sides, so the string "2\n" is converted to a number - by taking the leading number-looking portion and throwing away the rest. So the result of $i ^ 2 . "\n" is ultimately the same as $i ^ 2. Your "\n" didn't have any effect at all, so all the results are printed with nothing between them. 3, 0, 1, 6, ... became 3016...
^ is the Bitwise Xor operator
To square a number, you want the Exponentiation operator **
for my $i ( 1 .. 9 ) {
print $i**2, "\n";
}
Outputs:
1
4
9
16
25
36
49
64
81
foreach my $i (1..9){
say $i**2;
}
It can be achieve by doing this way also:
for (1..9) {
print $_*$_,"\n"
}
Output:
1
4
9
16
25
36
49
64
81
You can use the code below to get the squares.
print $_**2,"\n" for 1..10;
Related
I am new to Perl. An exercise, where I am to create a numeric ruler from which, I size columns for data at 20 characters-width, is proving a little difficult to complete. So far, I have,
printf “%10d” x 5, (1..6);
#ruler = (1..10) x 7;
Print #ruler, “\n”;
It should look something like,
1 2 3 4
1234567890123456789012345678901234567890
What I get for the top row of numbers is an error, ‘Redundant argument in printf at <script.pl> line #; the bottom row produces numbers from 1 to 10, as it ought with the range operator, but I would like it to produce 1 to 9 with a zero on the end. I did think to start the range from 0, but I haven’t figured out how to remove the first index and only the first index.
I would be grateful for your guidance with both issues.
The warning is due to the fact that you pass 6 numbers to printf, but the format only requires 5.
To me,
1 2 3 4
1234567890123456789012345678901234567890
reads as
11, 12, 13, ..., 19, 10, 21, 22, 23, ...
Why does it start with 11? Why is 10 between 19 and 21?
The following makes more sense:
1 2 3 4
01234567890123456789012345678901234567890 0-based
and
1 2 3 4
1234567890123456789012345678901234567890 1-based
I'm not going to give the solution outright.
If you want the numbers 1 to 9 and 0, that would be 1..9, 0.
%10d will add padding on the left. %-10d will add padding on the right.
Nothing says you can't prefix the output with something that doesn't repeat, like a zero or a space.
Provided desired output starts count from 11 instead 1 -- it doesn't look right.
Perhaps OP intended to start count from 1 until some $max value with placing a digit representing tens above main counter.
Please study following code sample for compliance with your requirements.
use strict;
use warnings;
use feature 'say';
my $max = shift || 45;
rule($max);
sub rule {
my $max = shift;
my($a,$b);
$a .= ' ' x 9 . $_ for 1..$max/10;
$b .= $_ % 10 for 1..$max;
say $a . "\n" . $b;
}
Output
1 2 3 4
123456789012345678901234567890123456789012345
Original OP's code requires slight modification to achieve desired output
use strict;
use warnings;
use feature 'say';
my $max = shift || 45;
printf "%10d" x int($max/10) . "\n", (1..$max/10);
print $_ % 10 for 1..$max;
print "\n";
Input log file:
Nservdrx_cycle 4 servdrx4_cycle
HCS_cellinfo_st[10] (type = (LTE { 2}),cell_param_id = (28)
freq_info = (10560),band_ind = (rsrp_rsrq{ -1}),Qoffset1 = (0)
Pcompensation = (0),Qrxlevmin = (-20),cell_id = (7),
agcreserved{3} = ({ 0, 0, 0 }))
channelisation_code1 16/5 { 4} channelisation_code1
sync_ul_info_st_ (availiable_sync_ul_code = (15),uppch_desired_power =
(20),power_ramping_step = (3),max_sync_ul_trans = (8),uppch_position_info =
(0))
trch_type PCH { 7} trch_type8
last_report 0 zeroth bit
I was trying to extract only integer for my above inputs but I am facing some
issue with if the string contain integer at the beginning and at the end
For ( e.g agcreserved{3},HCS_cellinfo_st[10],Qoffset1)
here I don't want to ignore {3},[10] and 1 but in my code it does.
since I was extracting only integer.
Here I have written simple regex for extracting only integer.
MY SIMPLE CODE:
use strict;
use warnings;
my $Ipfile = 'data.txt';
open my $FILE, "<", $Ipfile or die "Couldn't open input file: $!";
my #array;
while(<$FILE>)
{
while ($_ =~ m/( [+-]?\d+ )/xg)
{
push #array, ($1);
}
}
print "#array \n";
output what I am getting for above inputs:
4 4 10 2 28 10560 -1 1 0 0 -20 7 3 0 0 0 1 16 5 4 1 15 20 3 8 0 7 8 0
expected output:
4 2 28 10560 -1 0 0 -20 7 0 0 0 4 15 20 3 8 0 7 0
If some body can help me with explanation ?
You are catching every integer because your regex has no restrictions on which characters can (or can not) come before/after the integer. Remember that the /x modifier only serves to allow whitespace/comments inside your pattern for readability.
Without knowing a bit more about the possible structure of your output data, this modification achieves the desired output:
while ( $_ =~ m! [^[{/\w] ( [+-]?\d+ ) [^/\w]!xg ) {
push #array, ($1);
}
I have added rules before and after the integer to exclude certain characters. So now, we will only capture if:
There is no [, {, /, or word character immediately before the number
There is no / or word character immediately after the number
If your data could have 2-digit numbers in the { N} blocks (e.g. PCH {12}) then this will not capture those and the pattern will need to become much more complex. This solution is therefore quite brittle, without knowing more of the rules about your target data.
Is there a way to use Perl's range operator .. to use letters AND numbers?
For example, have:
for my $i ('X'..'9') {
print "$i ";
}
output X Y Z 1 2 3 4 5 6 7 8 9
Not unless for my $i ('X' .. 'Z', 1 .. 9) counts. "Z" will never increment to 1.
I've been messing around with writing FizzBuzz in perl...to be specific I want to make a nightmare looking line of code just to see if I can do it. This means nested ternary statements of course!
However I'm finding that on the 15's it never prints FizzBuzz, just Fizz. I cannot find a reason because that implies that if the first ternary statement returns true it's just skipping the second statement.
Here's the little nightmare I've come up with. Yes it can be way worse, but I'm really not that strong with perl and this is just an exercise for myself:
#!/usr/bin/perl
for (my $i=1; $i<=100; $i++) {
( !( ($i % 3 == 0) ? print "Fizz" : 0) && !( ($i % 5 == 0) ? print "Buzz" : 0) ) ? print "$i\n" : print "\n";
}
Here's the first 20 lines of output:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
Fizz
16
17
Fizz
19
Buzz
What would the print statement be doing that would cause this to happen?
This is an example of short-circuit evaluation, as documented in perlop. In cases of a() && b(), b() will never be evaluated if a() is false. In your (deeply nested and confusing) ternary statement, that amounts to the same thing. To fix this I'd split the statement up into multiple lines.
Simplified:
for my $i ( 1 .. 20 ) {
print +( ( $i % 3 ? '' : 'Fizz' ) . ( $i % 5 ? '' : 'Buzz' ) ) || $i, "\n";
}
Outputs:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
Actually, here we go, bit shifting saves the day
#!/usr/bin/perl
for (my $i=1; $i<=100; $i++) {
(((($i % 3 == 0) ? print "Fizz" : 0) + ( ($i % 5 == 0) ? print "Buzz" : 0)) << 1) ? print "\n" : print "$i\n";
}
Output:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
The most klugey solution
I have just started learning Perl, hence my question might seem very silly. I apologize in advance.
I have a list say #data which contains a list of lines read from the input. The lines contain numbers that are separated by (unknown number of) spaces.
Now, I would like to sort them and print them out, but not in the lexicographical order but according to the numerical value of the first number appearing on the line.
I know this must be something very simple but I cannot figure out how to do it?
Thanks in advance,
You can use a Schwartzian transform, capturing the first number in the row with a regex
use strict;
use warnings;
my #sorted = map $_->[0],
sort { $a->[1] <=> $b->[1] }
map { [ $_, /^(-?[\d.]+)/ ] } <DATA>;
print #sorted;
__DATA__
21 13 14
0 1 2
32 0 4
11 2 3
1 3 3
Output:
0 1 2
1 3 3
11 2 3
21 13 14
32 0 4
Reading the transform from behind, the <DATA> is the file handle we use, it will return a list of the lines in the file. The first map statement returns an array reference [ ... ], that contains the original line, plus the first number that is captured in the line. Alternatively, you can use the regex /^(\S+)/ here, to just capture whatever non-whitespace that comes first. The sort uses this captured number inside the array ref when comparing lines. And finally, the last map converts the array ref back to the original value, stored in $_->[0].
Be aware that this relies on the lines having a number at the start of the line. If that can be missing, or blank, this will have some unforeseen consequences.
Note that only using a simple numerical sort will also "work", because Perl will convert one of your lines to the correct number, assuming each line begins with a number followed by space. You will have some warnings about that, such as Argument "21 13 14\n" isn't numeric in sort. For example, if I replace my code above with
my #foo = sort { $a <=> $b } <DATA>;
I will get the output:
Argument "21 13 14\n" isn't numeric in sort at foo.pl line 6, <DATA> line 5.
Argument "0 1 2\n" isn't numeric in sort at foo.pl line 6, <DATA> line 5.
Argument "32 0 4\n" isn't numeric in sort at foo.pl line 6, <DATA> line 5.
Argument "11 2 3\n" isn't numeric in sort at foo.pl line 6, <DATA> line 5.
Argument "1 3 3\n" isn't numeric in sort at foo.pl line 6, <DATA> line 5.
0 1 2
1 3 3
11 2 3
21 13 14
32 0 4
But as you can see, it has sorted correctly. I would not advice this solution, but it is a nice demonstration in this context, I think.
You can use the sort function :
#sorted_data = sort(#data);