Jump to content

Resistance calculator: Difference between revisions

m
→‎{{header|Perl}}: subroutine signatures and code tweaks
m (syntax highlighting fixup automation)
m (→‎{{header|Perl}}: subroutine signatures and code tweaks)
Line 571:
===Infix===
{{trans|Raku}}
<syntaxhighlight lang="perl">use strictv5.36;
use warnings;
use feature <say state>;
 
{
package Resistor;
require Exporter;
our @ISA = qw(Exporter);
our @EXPORT = qw(set_voltage report);
 
use overload '+' => \&serial, '*' => \&parallel;
sub new {
 
sub mynew ($class, $args) = @_;{
my $self = {
symbol => $args->{symbol},
Line 590 ⟶ 591:
}
 
sub res ($self) {
my $self = shift;
if ($self->{symbol} eq '+') { return res($self->{a}) + res($self->{b}) }
elsif ($self->{symbol} eq '*') { return 1 / (1/res($self->{a}) + 1/res($self->{b})) }
else { return $self->{resistance} }
}
 
sub set_voltage ($self,$voltage) {
my($self,$voltage) = @_;
if ($self->{symbol} eq '+') {
my $ra = res($self->{a});
Line 611 ⟶ 610:
}
 
sub current { my ($self) = shift;{ return $self->{voltage} / res($self) }
sub effect { my ($self) = shift;{ return $self->{voltage} * current($self) }
 
use overload '+' => \&serial,
'*' => \&parallel;
 
sub serial { my($a,$b,$) = @_;{ Resistor->new( {symbol => '+', a => $a, b => $b} ) }
sub parallel { my($a,$b,$) = @_;{ Resistor->new( {symbol => '*', a => $a, b => $b} ) }
 
sub report ($self,$level = 0) {
my($self,$level) = @_;
state @results;
push @results, ' Ohm Volt Ampere Watt Network tree' and $level = 1 unless $level;
Line 635 ⟶ 630:
 
package main;
Resistor->import;
 
my ($R1, $R2, $R3, $R4, $R5, $R6, $R7, $R8, $R9, $R10) =
Line 642 ⟶ 638:
* $R4 + $R3) * $R2 + $R1;
 
Resistor::set_voltage($node,18);
say Resistor::report($node);</syntaxhighlight>
{{out}}
<pre style="height:20ex"> Ohm Volt Ampere Watt Network tree
10.000 18.000 1.800 32.400 | +
4.000 7.200 1.800 12.960 | | *
2,392

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.